Kubernetes v1.37正式GA:Metrics API毕业+Pod证书原生管理实战

Kubernetes v1.37 于 2026 年 8 月 26 日正式进入 GA(General Availability)阶段,此次版本在可观测性基础设施和密码学安全体系上均取得关键突破。Metrics API(metrics.k8s.io)从 beta 走向 stable,配合新增的 Pod Certificate API,为集群的自动扩缩容与零信任身份体系奠定了标准化基础。本文将从原理到实战,全面解析这两个特性在生产环境中的落地路径。

Metrics API GA 的核心意义

在 v1.37 之前,metrics-server 虽然已经成为事实上的标准组件,但其 API 始终停留在扩展 API 服务阶段,缺乏正式的稳定版承诺。GA 之后,metrics.k8s.io/v1 成为官方稳定 API,这意味着:

  • API 契约不可逆:字段变更需遵循正式的 API 升级政策,下游工具可以放心依赖。

  • 默认内置:新版集群中 metrics-server 以 Addon 形式随 K8s 镜像一同分发,不再需要手动部署。

  • HPA 原生集成:Horizontal Pod Autoscaler 直接调用稳定 API,无需额外的自定义资源桥接。

架构组件拆解

┌─────────────────────────────────────────────────────┐
│                    kube-apiserver                     │
│  ┌──────────────┐   ┌───────────────────────────┐   │
│  │  metrics.k8s.io│   │  /api/v1/nodes/metrics    │   │
│  │    REST       │──▶│  /api/v1/pods/{name}/...  │   │
│  └──────────────┘   └───────────────────────────┘   │
└────────────────────────┬────────────────────────────┘
                         │ HTTP/REST
┌────────────────────────▼────────────────────────────┐
│                  metrics-server                      │
│  ┌────────────────┐   ┌──────────────────────────┐  │
│  │  NodeCollector  │   │   PodCollector           │  │
│  │  (cAdvisor+)   │──▶│  (cAdvisor+containerd)   │  │
│  └────────────────┘   └──────────────────────────┘  │
│  ┌────────────────────────────────────────────┐     │
│  │          In-Memory Cache (TTL=60s)         │     │
│  └────────────────────────────────────────────┘     │
└─────────────────────────────────────────────────────┘
                         ▲
                         │ scrape
┌────────────────────────▼────────────────────────────┐
│              kubelet (每个 Node)                      │
│  /metrics/cadvisor endpoint                          │
└─────────────────────────────────────────────────────┘

Pod 证书原生管理:从零信任到自动化

v1.37 引入的 CertificateSigningRequest(CSR)增强模块支持 Pod 身份的自动签发。传统方案依赖外部 CA(如 Vault、CFSSL),现在集群内部即可闭环。

签发流程详解

Pod 启动
  │
  ▼
kubelet 检测证书即将过期(< 24h)
  │
  ▼
生成 CSR 对象,签名请求指向 Node Authorizer
  │
  ▼
apiserver 验证 Pod 身份 → 审批 CSR
  │
  ▼
kubelet 拉取签发的 x509 证书
  │
  ▼
挂载至 /var/run/secrets/kubernetes.io/podcerts

生产配置示例

# pod-certificate-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: pod-certificate-config
  namespace: kube-system
data:
  # 证书有效期(默认 8760h = 1 年)
  cert-ttl: "8760h"
  # 提前续期阈值
  renew-before: "24h"
  # 签发者 DN
  issuer-org: "kubernetes.default.svc"
  issuer-common-name: "kubernetes-pod-signer"
  # allowed usages
  key-usage: |
    digital signature
    key encipherment
    client auth
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
  name: pod-auto-sign
spec:
  signerName: kubernetes.io/kube-apiserver-client
  expirationSeconds: 8760
  usages:
    - client auth
  request:conditions:
    - type: Approved
      reason: AutoApprovePod

部署 Node Authorizer 以自动审批:

# 启用 Node 自动批准策略
cat <<'EOF' | kubectl apply -f -
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: node-auto-approve-certs
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:node-auto-approve-certs
subjects:
  - kind: Group
    name: system:nodes
    apiGroup: rbac.authorization.k8s.io
EOF

HPA v2beta3 与 Metrics API 深度集成

HPA 在 v1.37 中可以直接引用 metrics.k8s.io/v1 指标,无需再依赖 custom-metrics-adapter。

# hpa-metrics-integration.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web-app-hpa
  namespace: production
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web-app
  minReplicas: 3
  maxReplicas: 20
  metrics:
    # CPU 指标(内置)
    - type: Pod
      pod:
        resource: cpu
        target:
          type: Utilization
          averageUtilization: 70
    # 内存指标(内置)
    - type: Pod
      pod:
        resource: memory
        target:
          type: Utilization
          averageUtilization: 80
    # 自定义指标(仍走 custom-metrics-adapter)
    - type: Pods
      pods:
        metric:
          name: http_requests_per_second
        target:
          type: AverageValue
          averageValue: "100"
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Percent
          value: 10
          periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
        - type: Percent
          value: 50
          periodSeconds: 60
        - type: Pods
          value: 4
          periodSeconds: 60
      selectPolicy: Max

验证 HPA 状态:

kubectl get hpa web-app-hpa -n production -w

# 手动触发扩容测试
kubectl run load-test \
  --image=busybox \
  --command -- sh -c "while true; do wget -q -O- http://web-app:80/; done"

# 查看当前 Pod 指标
kubectl top pod -n production

kubectl top 命令的工作原理

kubectl top 通过聚合层调用 metrics-server,返回聚合数据:

# 查看 Node 资源使用
kubectl top node
# 输出示例:
# NAME          CPU(cores)   MEMORY(bytes)
# node-01       850m         4200Mi
# node-02       1200m        6100Mi

# 查看 Pod 资源使用
kubectl top pod -n production --containers
# NAME                    CPU(cores)   MEMORY(bytes)
# web-app-7d4f8b-x2k9     120m         256Mi
# web-app-7d4f8b-m3n7     95m          230Mi

# 指定精确时间窗口
kubectl top pod web-app-7d4f8b-x2k9 -n production

底层实现链路:

kubectl top pod
  └─ GET /apis/metrics.k8s.io/v1beta1/namespaces/{ns}/pods
       └─ Aggregator → metrics-server
            └─ GET /api/v1/nodes/{node}/proxy/metrics/cadvisor
                 └─ 返回 CPU(纳秒) + Memory(字节)

生产环境最佳实践

1. metrics-server 高可用部署

# metrics-server-ha.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: metrics-server
  namespace: kube-system
spec:
  replicas: 3
  selector:
    matchLabels:
      app: metrics-server
  template:
    metadata:
      labels:
        app: metrics-server
    spec:
      tolerations:
        - key: node-role.kubernetes.io/master
          effect: NoSchedule
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchExpressions:
                  - key: app
                    operator: In
                    values: [metrics-server]
              topologyKey: kubernetes.io/hostname
      containers:
        - name: metrics-server
          image: registry.k8s.io/metrics-server:v0.7.2
          args:
            - --kubelet-insecure-tls
            - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
            - --metric-resolution=15s
            - --container-image=registry.k8s.io/metrics-server:v0.7.2
            - --cert-dir=/tmp/tmp-metrics-server
          resources:
            requests:
              cpu: 100m
              memory: 256Mi
            limits:
              cpu: 500m
              memory: 512Mi

2. 证书自动轮换策略

# 配置 kubelet 证书自动轮换
# kubelet-config.yaml
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
certificateRotation:
  autoRotate: true
rotateCertificates: true
rotateServerCert: true
serverTLSBootstrap: true

3. 监控告警规则(Prometheus)

# prometheus-rules.yaml
groups:
  - name: k8s-metrics-alerts
    rules:
      - alert: MetricsServerUnreachable
        expr: up{job="metrics-server"} == 0
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "Metrics Server 不可达"

      - alert: PodCertExpiringSoon
        expr: |
          time() - last_transition_time{type="Approved",
            kind="CertificateSigningRequest"} < 86400
        for: 1h
        labels:
          severity: warning
        annotations:
          summary: "Pod 证书即将到期"

      - alert: HPAScalingStuck
        expr: |
          kube_horizontalpodautoscaler_status_current_replicas ==
          kube_horizontalpodautoscaler_spec_min_replicas
          and
          kube_horizontalpodautoscaler_status_desired_replicas ==
          kube_horizontalpodautoscaler_spec_min_replicas
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "HPA 扩缩容停滞"

版本升级注意事项

从 v1.36 升级至 v1.37 时,需注意以下兼容性事项:

  1. 停止依赖 beta 端点:旧版 metrics.k8s.io/v1beta1 已被移除,确保所有 HPA、Prometheus adapter 已切换至稳定 API。

  2. 证书策略变更:若此前使用了自定义 CA,升级后需在 kube-system 命名空间初始化默认签发者。

  3. 聚合层端口:metrics-server 需绑定到 443 而非 8080,升级前检查 Service 配置。

  4. RBAC 刷新:检查 system:metrics-server ClusterRole 是否包含新的 Pod 证书读取权限。

# 升级前检查清单
kubectl api-resources | grep metrics
kubectl get deployment metrics-server -n kube-system -o yaml
kubectl get csr | grep -v "Approved"

总结

Kubernetes v1.37 的 Metrics API GA 和 Pod 证书原生管理,标志着集群基础设施层迈向了更成熟的阶段。运维团队应重点关注 metrics-server 的 HA 部署、HPA 调优以及证书生命周期自动化,从而构建更可靠的观测与安全体系。建议在灰度环境中先行验证,确认指标准确性和证书续期无异常后再全量 rollout。