在 Kubernetes 中,如何基于 Label 实现 Gunicorn 的蓝绿切换并验证 Session 保持?

解读

这道题把“蓝绿发布”与“Session 亲和性”两个高频考点揉在一起,既考察候选人对 Kubernetes 原生对象(Deployment、Service、EndpointSlice)的熟悉度,也验证其能否把 Gunicorn 的无状态可水平扩展特性与有状态会话保持需求做权衡。面试官通常会在 10 分钟内追问三次:

  1. 蓝绿到底切的是哪一层?
  2. 零宕机怎么保证?
  3. 如果客户端带 Cookie,Gunicorn 默认进程内 Session 会不会丢?
    答不到“Pod 级 Label 重新 selector”和“Service 级 SessionAffinity 配置”这两个关键点,基本会被判定为“只背过概念,没上过生产”。

知识点

  1. 蓝绿发布本质:两套等价 Deployment(blue/green),通过同一 Service 的 selector 指向不同 Label完成流量瞬间切换;Kubernetes 层面无 Rollout,因此无 maxSurge/maxUnavailable 限制,可实现0 宕机。
  2. Gunicorn 无状态约束:worker 进程不共享内存,默认 Session 保存在本地内存。要实现 Session 保持,必须:
    a) 使用粘性会话(Service.spec.sessionAffinity=ClientIP 或 Cookie),让同一客户端始终落到同一 Pod;
    b) 或者把 Session 外置到Redis等共享存储,使蓝绿两套 Deployment 共用同一份 Session。
  3. Label 设计规范:
    • 版本号 Label 用 app.kubernetes.io/version: v1.2.3
    • 颜色标识用 release: blue|green
    • 共同基准 Label 用 app: order-api,保证 Service selector 可以只改一行完成切换。
  4. 零中断三板斧:
    • preStop hook 睡 15 秒,让 Gunicorn 处理完正在进行的请求;
    • terminationGracePeriodSeconds 设 30 秒,给长连接足够时间;
    • PodDisruptionBudget 保证最小可用副本数。
  5. 验证手段:
    • 用 kubectl set selector service/order-api release=green --record 切换后,持续压测 ab -c 50 -n 10000 -C "sessionid=xxx";
    • 观察Service 的 sessionAffinity 命中次数 kube_service_spec_session_affinity;
    • 若采用外置 Redis,通过 redis-cli monitor 查看 Session key 是否跨蓝绿共用。

答案

  1. 准备两套完全等价的 Gunicorn Deployment

    # deployment-blue.yaml
    metadata:
      name: order-api-blue
      labels: { app: order-api, release: blue, version: v1.1.0 }
    spec:
      replicas: 3
      template:
        metadata:
          labels: { app: order-api, release: blue, version: v1.1.0 }
        spec:
          containers:
          - name: gunicorn
            image: registry.cn-hangzhou.aliyuncs.com/acme/order-api:v1.1.0
            command: ["gunicorn", "-k", "gevent", "-w", "4", "--keep-alive", "2", "--max-requests", "1000", "--max-requests-jitter", "50", "wsgi:app"]
            lifecycle:
              preStop:
                exec:
                  command: ["/bin/sh", "-c", "sleep 15"]
            readinessProbe:
              httpGet: { path: /healthz, port: 8000 }
              initialDelaySeconds: 3
              periodSeconds: 5
    

    绿色版本仅把 release: green 与镜像 tag 换成 v1.2.0,其余完全一致。

  2. 创建公共 Service,显式开启 Session 亲和性

    apiVersion: v1
    kind: Service
    metadata:
      name: order-api
    spec:
      selector:
        app: order-api
        release: blue          # 初始指向蓝色
      sessionAffinity: ClientIP
      sessionAffinityConfig:
        clientIP:
          timeoutSeconds: 10800
      ports:
      - port: 80
        targetPort: 8000
    
  3. 执行蓝绿切换

    # 1. 先apply绿色Deployment,等待全部Pod Ready
    kubectl apply -f deployment-green.yaml
    kubectl wait deploy/order-api-green --for=condition=Available --timeout=300s
    
    # 2. 瞬间切换selector到绿色
    kubectl patch svc order-api -p '{"spec":{"selector":{"release":"green"}}}'
    
    # 3. 记录切换事件,方便回滚
    kubectl annotate svc order-api kubernetes.io/change-cause="switch to green v1.2.0 at $(date +%s)"
    
  4. 验证 Session 保持

    • ClientIP 模式:
      在集群内启动临时 Pod,执行
      for i in {1..100}; do curl -b "sessionid=user123" -c cookie.txt http://order-api/whoami; done
      观察返回的 Pod 名称始终为同一绿色 Pod,即会话粘性生效。
    • 外置 Redis 模式:
      把 Gunicorn 的 Session 中间件指向同一 Redis 集群,切换后再次请求,sessionid 未变且值可读取,证明蓝绿共用 Session。
  5. 回滚策略
    若监控 5xx 比例 >1%,立即执行
    kubectl patch svc order-api -p '{"spec":{"selector":{"release":"blue"}}}'
    30 秒内流量全部回到蓝色,实现秒级回滚。

拓展思考

  1. 灰度与蓝绿混用:在 Service 之上再套一层 Ingress-Nginx,利用 canary annotation 做 10% 流量灰度,剩余 90% 继续走蓝绿,兼顾风险控制与快速回滚。
  2. Session 零丢失改造:如果业务暂时无法外置 Redis,可在 Gunicorn 中启用 secure cookie + JWT,把全部状态下沉到客户端,彻底解除 Pod 与 Session 的耦合,实现“无状态蓝绿”。
  3. Pod 级优雅终止深度调优:Gunicorn 的 --graceful-timeout 与 Kubernetes 的 terminationGracePeriodSeconds 要同步对齐,否则会出现“Gunicorn 已退出,但 Pod 还在 Terminating”的僵尸状态,导致 Prometheus 仍把该 Pod 计入可用副本。
  4. 大规模集群性能陷阱:当副本数 >500 时,Service 的 iptables 模式会出现概率性 Session 漂移,可升级为 ipvs 模式 或直接使用 Traefik/ServiceMesh 做四层负载,保证 Session 亲和性在高并发下依旧稳定。