结合 Flagger,如何按 10 % 流量递增把新版本的 Gunicorn 实例接入?
解读
面试官想知道你是否真的在生产环境做过渐进式灰度发布,而不是只会“kubectl set image”。
国内大厂(阿里、字节、美团)普遍用 Flagger + Istio/Contour 做流量治理,核心指标是成功率、P99 延迟、5xx 比例。
10 % 步长只是表象,背后必须回答:
- 谁决定“下一步”?——Flagger 的自动校验与回滚策略
- 流量怎么切?——Istio VirtualService 的 weight 字段
- Gunicorn 自身如何无损重启并暴露指标?——pre_fork 模型 + Prometheus 端点
- 国内云厂商(ACK、TKE、CCE)对 Sidecar 注入、LB 带宽、连接数上限 的特殊限制
答不到这四点,会被直接判定为“只看过文档”。
知识点
- Flagger Canary CRD:spec.analysis 里定义 stepWeight: 10,maxWeight: 100,threshold: 5(连续 5 次校验通过才继续)
- Istio VirtualService 流量拆分:http.route.weight 字段由 Flagger 控制器实时 patch,无需手动改 YAML
- Gunicorn 指标暴露:
- 启动参数
--statsd-host或--prometheus-port 9200 - 自定义
gunicorn_config.py里写def child_exit(server, worker): prometheus_client.multiprocess.mark_process_dead(worker.pid)解决 多 worker 指标漂移
- 启动参数
- pre-stop hook:lifecycle.preStop.exec.command 先
sleep 15再kill -QUIT 1,给 Arbitrary 连接优雅收尾(国内 LB 默认 30 s 才摘流) - 回滚触发条件:
- 成功率 < 99 %
- P99 > 500 ms
- 5xx/4xx 环比上升 > 5 %
满足任一条件,Flagger 立即把 weight 改回 0,并 scale new revision to 0
- 国内踩坑:
- ACK 的 SLB 默认 短连接 5 s 超时,需把
worker_keepalive 75调大 - TKE 的 CLB 重试次数=3,会把 502 放大成雪崩,要在 VirtualService 里加 retries.attempts=0
- 私有镜像仓库拉取限速,导致新 Pod 起不来,Flagger 误判为“指标不达标”,需给 ImagePullSecrets + 预热 DaemonSet
- ACK 的 SLB 默认 短连接 5 s 超时,需把
答案
-
准备镜像与指标
新版本的 Dockerfile 末尾加
RUN pip install prometheus-client==0.16
gunicorn_config.py 里暴露/metrics端口 9200,并解决 多 worker 数据漂移。 -
定义 Canary 对象
apiVersion: flagger.app/v1beta1 kind: Canary metadata: name: gunicorn-demo namespace: prod spec: targetRef: apiVersion: apps/v1 kind: Deployment name: gunicorn-demo progressDeadlineSeconds: 600 service: port: 80 targetPort: 8000 gateways: - public-gateway.istio-system.svc.cluster.local hosts: - api.xxx.com analysis: interval: 1m threshold: 5 maxWeight: 100 stepWeight: 10 metrics: - name: request-success-rate thresholdRange: min: 99 interval: 1m - name: request-duration thresholdRange: max: 500 interval: 1m webhooks: - name: load-test url: http://flagger-loadtester.prod/ timeout: 30s metadata: cmd: "hey -z 2m -q 100 -c 10 http://api.xxx.com/health" -
触发发布
更新 Deployment 的镜像 tag,Flagger 检测到新版后会:- 先缩容到 零实例 → 拉起 1 个新版 Pod(权重 0)
- 第一次 step 把 VirtualService weight=10,老版本 90
- 每分钟校验一次指标,连续 5 次通过 再 +10 %,否则立即回滚
- 达到 100 % 后,把 Canary 状态标记为 Succeeded,并删除旧版 ReplicaSet
-
Gunicorn 无损重启
在 Deployment 的 lifecycle 里加preStop: exec: command: ["/bin/sh", "-c", "sleep 15 && kill -QUIT 1"]配合
worker_graceful_timeout = 30,确保 SLB 摘流 + 连接收尾 完成。 -
回滚演练
手动注入 502:kubectl exec -n prod deploy/gunicorn-demo-new -c gunicorn -- pkill -9 gunicorn
10 s 内 Flagger 会收到成功率下跌,30 s 内完成流量归零,并发出 钉钉/飞书告警(通过 AlertManager webhook)。
拓展思考
- 多集群灰度:国内金融客户要求“上海集群→深圳集群”双活,可用 Flagger + Karmada 做 跨集群 Canary,通过 DNS 权重 + Istio ServiceEntry 把 10 % 流量切到远端集群,需解决 跨 AZ 延迟基线 问题。
- 零信任场景:在 Istio 1.18 + STRICT mTLS 下,Gunicorn 必须 关闭 keep-alive,否则 sidecar 会报
upstream connect error,需要在 VirtualService 里加 connectionPool.tcp.maxConnections=10 限流。 - 成本优化:大促前压测发现 10 % 步长太慢,可临时把 stepWeight 改成 20,但需把 threshold 提高到 10 防止误判;压测完再改回 10 %,实现 “快上慢下” 策略。