Kubernetes HPA 与 VPA:自动扩缩容实战
手动调整 Pod 副本数和资源配额是运维的噩梦,HPA 和 VPA 能让 K8s 自动完成这件事。
HPA:水平扩缩容
HPA 根据指标自动调整 Pod 副本数。
基于 CPU 的 HPA
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-app-hpa
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70 # CPU 使用率超过 70% 开始扩容
behavior:
scaleUp:
stabilizationWindowSeconds: 60 # 扩容冷却 60 秒
policies:
- type: Percent
value: 100
periodSeconds: 60 # 每分钟最多翻倍
scaleDown:
stabilizationWindowSeconds: 300 # 缩容冷却 5 分钟,避免抖动
policies:
- type: Percent
value: 20
periodSeconds: 60 # 每分钟最多缩减 20%
基于自定义指标的 HPA
需要安装 Prometheus Adapter:
metrics:
- type: Pods
pods:
metric:
name: http_requests_per_second
target:
type: AverageValue
averageValue: "1000" # 每个 Pod 处理 1000 QPS
查看 HPA 状态
# 查看当前扩缩容状态
kubectl get hpa -n production
# 详细信息,包括触发原因
kubectl describe hpa my-app-hpa -n production
# 实时观察
kubectl get hpa -n production -w
VPA:垂直扩缩容
VPA 自动调整容器的 CPU/Memory requests 和 limits。
安装 VPA
git clone https://github.com/kubernetes/autoscaler.git
cd autoscaler/vertical-pod-autoscaler
./hack/vpa-up.sh
VPA 配置
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: my-app-vpa
namespace: production
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
updatePolicy:
updateMode: "Auto" # Auto/Recreate/Initial/Off
resourcePolicy:
containerPolicies:
- containerName: app
minAllowed:
cpu: 100m
memory: 128Mi
maxAllowed:
cpu: 4
memory: 4Gi
controlledResources: ["cpu", "memory"]
updateMode 说明:
Off:只给建议,不自动修改Initial:只在 Pod 创建时设置Auto:自动更新(会重建 Pod)
查看 VPA 建议
kubectl describe vpa my-app-vpa -n production
输出示例:
Recommendation:
Container Recommendations:
Container Name: app
Lower Bound: cpu: 50m, memory: 128Mi
Target: cpu: 200m, memory: 512Mi ← 建议值
Upper Bound: cpu: 1, memory: 2Gi
HPA 与 VPA 同时使用
不建议同时对 CPU/Memory 使用 HPA 和 VPA,会产生冲突。推荐方案:
- HPA 基于 CPU/自定义指标做水平扩缩
- VPA 设置为
Off模式,只用于获取资源配置建议 - 定期根据 VPA 建议手动调整 requests/limits
常见问题
HPA 不触发扩容?
# 检查 metrics-server 是否正常
kubectl top pods -n production
# 检查 HPA 事件
kubectl describe hpa my-app-hpa | grep -A20 Events
扩容太慢?
调小 scaleUp.stabilizationWindowSeconds,或增大 policies.value。
频繁扩缩容(抖动)?
调大 scaleDown.stabilizationWindowSeconds,建议不低于 300 秒。