1. 设计灰度发布策略
- 服务版本管理:
- 在Docker镜像仓库(如Harbor)中为新功能版本和旧版本分别创建对应的镜像标签。例如,旧版本镜像标签为
v1.0
,新功能版本镜像标签为v2.0
。
- 流量控制规划:
- 利用Kubernetes的Ingress或Service Mesh(如Istio)来控制流量比例。对于Ingress,可以通过配置
annotations
来实现流量的分流;对于Istio,可以利用VirtualService
和DestinationRule
资源对象进行精确的流量管理。
2. 实施灰度发布
- 创建Kubernetes Deployment:
- 为旧版本创建Deployment,例如
old - version - deployment.yaml
:
apiVersion: apps/v1
kind: Deployment
metadata:
name: old - version - deployment
spec:
replicas: 3
selector:
matchLabels:
app: my - app
version: v1.0
template:
metadata:
labels:
app: my - app
version: v1.0
spec:
containers:
- name: my - app - container
image: your - registry/your - app:v1.0
ports:
- containerPort: 8080
- 为新版本创建Deployment,例如
new - version - deployment.yaml
:
apiVersion: apps/v1
kind: Deployment
spec:
replicas: 1
selector:
matchLabels:
app: my - app
version: v2.0
template:
metadata:
labels:
app: my - app
version: v2.0
spec:
containers:
- name: my - app - container
image: your - registry/your - app:v2.0
ports:
- containerPort: 8080
- 配置流量控制:
- 使用Ingress:
在Ingress资源对象中添加
nginx.ingress.kubernetes.io/service - weights
注解,例如:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my - app - ingress
annotations:
nginx.ingress.kubernetes.io/service - weights: 'old - version - service:90,new - version - service:10'
spec:
rules:
- host: your - domain.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: old - version - service
port:
number: 8080
- path: /
pathType: Prefix
backend:
service:
name: new - version - service
port:
number: 8080
- 使用Istio:
创建
VirtualService
和DestinationRule
:
# VirtualService
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: my - app - virtual - service
spec:
hosts:
- your - domain.com
http:
- route:
- destination:
host: old - version - service
subset: v1.0
weight: 90
- destination:
host: new - version - service
subset: v2.0
weight: 10
# DestinationRule
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: my - app - destination - rule
spec:
host: old - version - service
subsets:
- name: v1.0
labels:
version: v1.0
host: new - version - service
subsets:
- name: v2.0
labels:
version: v2.0
3. 监控环节
- 指标监控:
- 使用Prometheus收集容器和服务的各项指标,如CPU使用率、内存使用率、请求响应时间、请求成功率等。为不同版本的服务配置不同的标签,以便区分监控数据。
- 在Grafana中创建仪表盘,展示这些指标数据,实时观察新版本和旧版本服务的运行状况。
- 日志监控:
- 配置容器日志收集,例如使用Fluentd将容器日志发送到Elasticsearch。在Kibana中可以通过设置过滤器,按服务版本筛选日志,及时发现新版本可能出现的问题。
4. 回滚环节
- 手动回滚:
- 如果在灰度发布过程中发现新版本出现严重问题,立即通过Kubernetes命令或Kubernetes Dashboard删除新版本的Deployment,并将旧版本Deployment的副本数恢复到初始状态。
- 例如,使用
kubectl delete deployment new - version - deployment
删除新版本Deployment,使用kubectl scale deployment old - version - deployment --replicas = 5
(假设初始副本数为5)恢复旧版本Deployment的副本数。
- 自动回滚:
- 利用Kubernetes的
RollingUpdate
策略中的maxUnavailable
和maxSurge
参数,结合监控指标设置自动回滚机制。例如,如果新版本服务的请求成功率低于某个阈值(如90%),Kubernetes自动触发回滚,将流量全部切回旧版本。可以通过编写自定义的监控脚本,调用Kubernetes API实现这一功能。