Kevin
395 words
2 minutes
kubernetes-hpa

1. HPA 简介#

自动调整 Pod 的副本数。横向扩展(scale out/in)


2. HPA 工作原理#

HPA 依赖 Kubernetes Metrics API 获取指标数据,计算合适的 Pod 副本数,并更新 Deployment、ReplicaSet 或 StatefulSetspec.replicas

HPA 的基本工作流程如下:

  1. 采集指标:HPA 通过 Metrics Server自定义指标(Custom Metrics API) 获取当前 Pod 负载,如 CPU/内存使用率。
  2. 计算期望副本数
    • 根据定义的目标值(Target)计算 Pod 需要多少副本才能满足需求。
    • 计算公式: 目标副本数=当前副本数×当前指标值目标指标值目标副本数 = \frac{当前副本数 \times 当前指标值}{目标指标值}
  3. 调整副本数:HPA 根据计算结果修改 replicas,自动扩展或缩容。

3. HPA 的核心组件#

  1. Metrics Server

  2. HPA 控制器

    • 定期(默认 15 秒)从 Metrics Server 获取指标数据。
    • 计算是否需要扩展/缩容,并修改 replicas

4. HPA 配置示例#

  • 目标:当 CPU 使用率超过 50% 时,HPA 自动扩展 Pod 数量。

  • 创建 Deployment

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: nginx-deployment
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: nginx
      template:
        metadata:
          labels:
            app: nginx
        spec:
          containers:
            - name: nginx
              image: nginx
              resources:
                requests:
                  cpu: "250m"
                limits:
                  cpu: "500m"
    
  • 创建 HPA:

    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: nginx-hpa
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: nginx-deployment
      minReplicas: 1
      maxReplicas: 10
      metrics:
        - type: Resource
          resource:
            name: cpu
            target:
              type: Utilization
              averageUtilization: 50
    
  • 查看 HPA 状态:

    kubectl get hpa
    

5. HPA 关键参数#

参数说明
minReplicas最小副本数
maxReplicas最大副本数

6. HPA 进阶#

防止抖动(Stabilization Window) - 扩展操作可快速响应,而缩容应保持谨慎:

behavior:
      scaleDown:
	    stabilizationWindowSeconds: 300  # 5 分钟稳定期

kubernetes-hpa
https://fuwari.vercel.app/posts/kubernetes-hpa/kubernetes-hpa/
Author
Kevin
Published at
2025-03-09