使用 autoscaling/v2 基于 QPS 指标自动扩缩 Ingress 控制器副本

解读

在国内云原生面试中,这道题考察的是“把 Nginx Ingress 控制器当成有状态微服务”来治理的能力。
核心不是写一段 YAML,而是证明你:

  1. 知道 QPS 不是 Kubernetes 原生指标,必须自己“喂”给 HPA;
  2. 能把 Nginx 的实时 QPS 无损地暴露给 Prometheus,再转成 autoscaling/v2 认可的 external metric;
  3. 能在 1.27+ 集群里正确配置 behavior、scaleDown stabilization 与跨可用区打散,避免“一扩容就雪崩”;
  4. 能在灰度场景下区分“业务 QPS”与“控制器自身 QPS”,防止误扩。
    一句话:让面试官相信,你能在 10 万级并发下,30 秒内完成 2→20 副本的平滑扩容,且 CPU 利用率不到 40%。

知识点

  1. autoscaling/v2 API 字段:
    • type: External,metric.name 与 metric.selector 必须和 Prometheus Adapter 注册的名称完全匹配;
    • behavior.scaleDown/selectPolicy: Disabled 可临时禁止缩容;
    • 支持多指标加权,防止单指标抖动。
  2. Nginx Ingress 暴露 QPS 的三种姿势:
    • stub_status(默认 8080)只能拿到总连接数,需自己算 rate;
    • lua-prometheus 模块在 log_by_lua 阶段直接写 Prometheus 格式;
    • 官方 prometheus exporter 把 VTS 数据转成 histogram,最常用。
  3. Prometheus Adapter 的 config rule 写法:
    seriesQuery: nginx_ingress_controller_requests{namespace="ingress-nginx"}
    resources: {namespace: "namespace", pod: "pod"}
    name: {matches: "^(.*)_requests", as: "nginx_ingress_qps_per_pod"}
    metricsQuery: 'sum(rate(nginx_ingress_controller_requests[1m])) by (<<.GroupBy>>)'
  4. HPA 冷启动优化:
    • 把 kube-controller-manager 的 --horizontal-pod-autoscaler-sync-period 从默认 15s 调到 5s;
    • 给 Ingress Controller 加上 cluster-autoscaler 的 safe-to-evict 注解,防止扩容节点被误缩。
  5. 国内云厂商差异:
    • ACK 的 Prometheus Adapter 已内置 common nginx ingress 指标,但名字带 ack_ 前缀,需双写 rule;
    • TKE 要求 external.metrics.k8s.io 走内网 CLB,端口 443,需放通安全组。

答案

  1. 部署带 Prometheus 插件的 Nginx Ingress Controller
    使用官方 Helm chart,values 关键片段:
    controller.metrics.enabled: true
    controller.metrics.serviceMonitor.enabled: true
    controller.metrics.port: 10254
    确认 ServiceMonitor 被 Prometheus 抓取。

  2. 注册 External 指标
    在 Prometheus Adapter 的 configMap 新增 rule:

    - seriesQuery: nginx_ingress_controller_requests{namespace="ingress-nginx"}
      resources:
        overrides:
          namespace: {resource: "namespace"}
          pod:     {resource: "pod"}
      name:
        matches: "^(.*)_requests"
        as: "nginx_ingress_qps_per_pod"
      metricsQuery: |
        sum(rate(nginx_ingress_controller_requests[1m])) by (<<.GroupBy>>)
    

    重启 Adapter 后,执行

    kubectl get --raw /apis/external.metrics.k8s.io/v1beta1/namespaces/ingress-nginx/nginx_ingress_qps_per_pod
    

    能返回带 pod 维度的实时 QPS 即成功。

  3. 创建 HPA

    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: nginx-ingress-hpa
      namespace: ingress-nginx
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: ingress-nginx-controller
      minReplicas: 2
      maxReplicas: 50
      metrics:
      - type: External
        external:
          metric:
            name: nginx_ingress_qps_per_pod
            selector:
              matchLabels:
                namespace: ingress-nginx
          target:
            type: AverageValue
            averageValue: "1000"   # 单副本 1000 QPS
      behavior:
        scaleDown:
          stabilizationWindowSeconds: 300
          policies:
          - type: Percent
            value: 10
            periodSeconds: 60
        scaleUp:
          stabilizationWindowSeconds: 15
          policies:
          - type: Percent
            value: 100
            periodSeconds: 15
          - type: Pods
            value: 4
            periodSeconds: 15
          selectPolicy: Max
    

    解释:

    • 单副本 1000 QPS 为基线,来源于压测报告(4C8G 容器在开启 keepalive、HTTP2 时 80% CPU 对应 1000 QPS);
    • scaleUp 最快 15 秒翻倍,但一次最多加 4 个 Pod,防止突刺;
    • scaleDown 先观察 5 分钟,10% 步长,避免晚高峰后过早缩容。
  4. 灰度验证
    使用 Apache Bench 打流量:

    ab -n 1000000 -c 100 -k http://test.example.com/1k.html
    

    同时 watch:

    kubectl get hpa -n ingress-nginx -w
    

    观察到 TARGETS 列从 400% 降到 95% 左右,副本数由 2→8→14,停止压测 5 分钟后副本数缓慢回到 2,即验收通过。

  5. 生产加固

    • 给 HPA 加 annotations: "cluster-autoscaler.kubernetes.io/safe-to-evict": "false",防止节点缩容时把 Ingress Controller 一锅端;
    • 在 Adapter 侧加 record: nginx_ingress_qps_per_pod:5m 预聚合,降低查询延迟;
    • 把 HPA 指标同时接入阿里 SLS 或腾讯 CLS,做二次告警,避免 Adapter 挂掉导致盲扩。

拓展思考

  1. 多租户场景下,如何按“域名+路径”维度做更细粒度 QPS 指标?
    答:在 log_by_lua 里用 ngx.var.host 与 ngx.var.uri 拼 label,写入 Prometheus,Adapter 注册时带上 host、path 维度,HPA 用 metric.selector 匹配特定业务,实现“只扩支付网关,不扩静态站点”。

  2. 如果集群启用了 Pod Security Standard(restricted),Ingress Controller 需要 NET_BIND_SERVICE 能力,怎样既满足安全规范又保证 80/443 低端口?
    答:容器依旧跑 1024 以上端口,宿主机通过 hostPort 80/443 暴露;使用 Capabilities 仅保留 NET_BIND_SERVICE,并设置 seccompProfile 为 RuntimeDefault,可过 restricted 校验。

  3. 当 QPS 突增触发扩容后,新 Pod 需要预热 Lua 共享字典缓存,如何避免 502?
    答:在 readinessProbe 里加 httpGet 路径 /nginx-health,只有当缓存预热完成才返回 200;同时 HPA behavior 里加 scaleUp.selectPolicy: Min,放慢扩容节奏,让新 Pod 有时间完成预热。