在 Kubernetes 中,HPA(Horizontal Pod Autoscaler) 用于根据负载自动调整 Pod 副本数,是生产集群的基础能力之一。本文将从 命令行快速创建 到 生产级 YAML 配置,系统梳理 CPU / Memory HPA 的常用方式与最佳实践。
一、kubectl autoscale:快速创建 CPU HPA
1. 基本用法
kubectl autoscale deployment web \
--min=2 \
--max=10 \
--cpu-percent=75该命令会创建一个:
apiVersion: autoscaling/v1仅支持 CPU
基于
requests.cpu的 HPA
2. CPU 扩缩容原理
Pod 实际 CPU 使用率 / requests.cpu当平均 CPU 使用率 ≥ --cpu-percent,HPA 触发扩容。
⚠️ 前提条件
resources:
requests:
cpu: 200m未设置 requests.cpu → HPA 不生效。
3. kubectl autoscale 的限制
❌ 不支持 Memory
❌ 不支持多指标
❌ 不支持扩缩容行为控制
👉 适用场景
临时测试
Demo
快速验证 HPA 是否工作
二、YAML 方式(生产推荐)
生产环境中,推荐使用 autoscaling/v2 版本,功能更完整。
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler三、基于 CPU 的 HPA(YAML)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 75说明
75% =
CPU 使用量 / requests.cpurequests 是计算基准,而不是 limits
四、基于 Memory 的 HPA(YAML)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-hpa
spec:
minReplicas: 2
maxReplicas: 10
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
metrics:
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 70⚠️ 同样需要:
resources:
requests:
memory: 512Mi五、CPU + Memory 混合伸缩(常见生产写法)
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 75扩容逻辑
任一指标超过阈值,HPA 就会触发扩容。
六、基于绝对值的 HPA(AverageValue)
当 requests 不准确或内存模型特殊时,可使用绝对值。
metrics:
- type: Resource
resource:
name: memory
target:
type: AverageValue
averageValue: 500Mi适用场景
JVM 服务
缓存型应用
内存长期高水位但 requests 不好估算
七、扩缩容行为控制(强烈建议配置)
防止 Pod 数量频繁抖动。
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50
periodSeconds: 60含义
扩容:1 分钟内最多翻倍
缩容:5 分钟内稳定后再缩
八、kubectl autoscale vs YAML 对比
九、常见问题排查清单
Deployment 是否设置了
requests.cpu / memorymetrics-server 是否正常运行
是否使用 autoscaling/v2 配置 memory
业务是否存在单 Pod 热点
十、总结
kubectl autoscale:适合快速验证 CPU HPA
autoscaling/v2 YAML:生产环境标准方案
CPU / Memory 混合 + 行为控制,是最常见配置组合