Blue-Green 发布
Blue-Green 发布会同时运行两套版本:Active 版本承接生产流量,Preview 版本用于部署后验证。验证通过后,Rollout 将 Active Service 切换到新 ReplicaSet;验证失败时,生产流量仍留在旧版本。
1. 适用场景
Blue-Green 适合以下场景:
- 新版本需要完整启动后才能验证;
- 需要在生产集群中保留一个可访问但不接收生产流量的 Preview 环境;
- 希望一次切换生产入口,并在短时间内保留旧版本回退能力;
- 集群有足够容量同时运行两套副本。
它的代价是容量和成本更高。若服务副本数很大、镜像启动慢或数据库迁移不可兼容,应先评估容量和回滚窗口。
2. Rollout 与 Service 示例
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: checkout
namespace: production
spec:
replicas: 6
revisionHistoryLimit: 3
strategy:
blueGreen:
activeService: checkout-active
previewService: checkout-preview
# 新版本 Ready 后暂停,等待业务验证或 AnalysisRun
autoPromotionEnabled: false
scaleDownDelaySeconds: 300
previewReplicaCount: 6
antiAffinity:
requiredDuringSchedulingIgnoredDuringExecution: {}
selector:
matchLabels:
app: checkout
template:
metadata:
labels:
app: checkout
spec:
containers:
- name: app
image: registry.company.com/apps/checkout:v3.4.0
ports:
- name: http
containerPort: 8080
readinessProbe:
httpGet:
path: /ready
port: http
periodSeconds: 5
failureThreshold: 3
---
apiVersion: v1
kind: Service
metadata:
name: checkout-active
namespace: production
spec:
selector:
app: checkout
ports:
- name: http
port: 80
targetPort: http
---
apiVersion: v1
kind: Service
metadata:
name: checkout-preview
namespace: production
spec:
selector:
app: checkout
ports:
- name: http
port: 80
targetPort: http
activeService 和 previewService 的 selector 可以相同,Rollout Controller 会通过 Service selector 管理当前版本的 ReplicaSet。不要再用额外的手工 selector 覆盖 Controller 的切换结果。
3. 发布与确认流程
# 应用 Rollout 与 Service
kubectl apply -f checkout-bluegreen.yaml
# 查看新版本是否已创建并进入暂停
kubectl argo rollouts get rollout checkout -n production
# 访问 Preview Service 做接口、回归和数据库兼容性验证
kubectl port-forward service/checkout-preview -n production 18080:80
curl -fsS http://127.0.0.1:18080/ready
# 验证通过后切换 Active Service
kubectl argo rollouts promote checkout -n production
# 持续观察切换后的状态
kubectl argo rollouts get rollout checkout -n production --watch
如果使用 Ingress、Gateway API 或 Istio,Preview Service 还可以绑定单独的测试域名或受限路由。不要把 Preview 入口暴露给所有公网用户,除非应用已经具备认证和数据隔离能力。
4. 自动晋级与延迟缩容
autoPromotionEnabled: false:新版本 Ready 后暂停,适合需要人工验收的生产发布;autoPromotionSeconds:暂停指定秒数后自动切换,适合验证自动化且风险可控的服务;scaleDownDelaySeconds:切换后保留旧 ReplicaSet 一段时间,给连接排空和快速回滚留出窗口;previewReplicaCount:控制 Preview 副本数,不能低于验证所需容量。
自动晋级之前,至少应有 Readiness、关键接口探针和可执行的 AnalysisRun。单纯依赖固定等待时间无法发现错误率和延迟异常。
5. 回滚与清理
# 发现新版本异常时,终止当前发布
kubectl argo rollouts abort checkout -n production
# 检查 Active Service 当前指向的版本
kubectl get service checkout-active -n production -o yaml
kubectl argo rollouts get rollout checkout -n production
# 确认稳定版本后再清理旧 ReplicaSet;通常由 Controller 根据策略处理
kubectl get replicasets -n production -l app=checkout
不要直接删除 Preview Pod 或 ReplicaSet 来“修复”发布。这样会让 Rollout 状态与实际资源不一致,应该通过 abort、Git 回退或调整 Rollout 策略处理。