Kubernetes容器编排中自动伸缩是保障服务稳定性和资源利用率的关键能力。HPA(Horizontal Pod Autoscaler)根据CPU、内存或自定义指标水平扩展Pod数量,VPA(Vertical Pod Autoscaler)自动调整Pod的CPU和内存请求/限制。两者配合可以在流量波动的场景下实现精细化的资源管理,本文给出从安装到配置的完整实践。
Kubernetes HPA水平自动伸缩安装与基础配置
HPA依赖Metrics Server采集资源使用数据。先确认Metrics Server已部署:
kubectl top nodes
kubectl top pods -n default
如果命令返回数据说明Metrics Server正常。否则安装Metrics Server:
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
# 确认metrics-server Pod运行
kubectl get pods -n kube-system | grep metrics-server
创建一个测试Deployment并配置基于CPU利用率的HPA:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
spec:
replicas: 2
selector:
matchLabels:
app: web-app
template:
metadata:
labels:
app: web-app
spec:
containers:
- name: web-app
image: nginx:1.25
resources:
requests:
cpu: 200m
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi
ports:
- containerPort: 80
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-app
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 70
averageUtilization 60表示当Pod平均CPU使用率超过请求值的60%时触发扩容。注意HPA计算基准是requests值而非limits值,所以resources.requests必须正确设置。
HPA扩缩容行为参数调优
autoscaling/v2版本的HPA支持behavior字段,可以精细控制扩缩容速度,避免流量突增时扩容过慢或流量回落时缩容过快导致抖动:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-app
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 15
- type: Pods
value: 4
periodSeconds: 15
selectPolicy: Max
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 10
periodSeconds: 60
scaleUp的stabilizationWindowSeconds设为0表示立即响应扩容需求。Percent 100表示每15秒最多扩容当前副本数的100%(翻倍),Pods 4表示每15秒最多新增4个Pod,selectPolicy: Max取两者中较大的值。scaleDown的稳定窗口设为300秒(5分钟),即CPU恢复正常后还需观察5分钟才开始缩容,避免流量抖动导致频繁扩缩。
自定义指标驱动HPA伸缩
CPU和内存是通用指标,但很多场景需要基于QPS、消息队列深度等业务指标做伸缩决策。这需要部署Prometheus Adapter将Prometheus指标转换为Kubernetes自定义指标。
安装Prometheus Adapter:
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus-adapter prometheus-community/prometheus-adapter \
--set prometheus.url=http://prometheus-server.monitoring.svc.cluster.local \
--set prometheus.port=80
# 验证自定义指标API
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1" | jq .
配置Adapter规则将Prometheus中的http_requests_per_second指标映射为Kubernetes自定义指标:
rules:
- seriesFilters: []
seriesQuery: 'http_requests_per_second{namespace!="",pod!=""}'
resources:
overrides:
namespace: {resource: "namespace"}
pod: {resource: "pod"}
name:
matches: "^(.*)_per_second"
as: "${1}"
metricsQuery: 'sum(<<.Series>>{<<.LabelMatchers>>}) by (<<.GroupBy>>)'
然后在HPA中引用该自定义指标:
metrics:
- type: Pods
pods:
metric:
name: http_requests
target:
type: AverageValue
averageValue: "1000"
averageValue 1000表示当每Pod平均QPS超过1000时触发扩容。这种基于业务指标的伸缩策略能更准确地响应实际负载。
VPA垂直自动伸缩安装与运行模式
VPA自动调整Pod的resource requests值,适用于无法水平扩展的有状态服务或需要精确资源配额的场景。安装VPA组件:
git clone https://github.com/kubernetes/autoscaler.git
cd autoscaler/vertical-pod-autoscaler
./hack/vpa-up.sh
# 确认VPA组件运行
kubectl get pods -n kube-system | grep vpa
创建VPA资源,以Recommendation模式运行(只给出建议不实际修改):
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: web-app-vpa
spec:
targetRef:
apiVersion: "apps/v1"
kind: Deployment
name: web-app
updatePolicy:
updateMode: "Off" # 仅推荐,不自动应用
resourcePolicy:
containerPolicies:
- containerName: '*'
minReplicas: 2
maxReplicas: 20
controlledResources: ["cpu", "memory"]
updateMode可选值:Off(仅推荐)、Initial(仅在新Pod创建时应用建议)、Auto(自动调整,会重建Pod)。Auto模式下VPA会删除并重建Pod以应用新的资源配置,可能导致短暂的服务中断,需谨慎使用。
查看VPA推荐值:
kubectl describe vpa web-app-vpa
# 输出示例:
# Recommendation:
# Target: cpu 350m, memory 400Mi
# Lower Bound: cpu 200m, memory 256Mi
# Upper Bound: cpu 800m, memory 768Mi
HPA与VPA协同使用的注意事项
HPA和VPA不能同时对同一资源维度工作。如果HPA基于CPU利用率伸缩,VPA就不能自动调整CPU requests。实际部署中推荐的组合方案是:对无状态服务使用HPA水平扩展,对有状态服务或难以水平扩展的服务使用VPA垂直扩展。
监控HPA运行状态的关键命令:
# 查看HPA当前状态和伸缩事件
kubectl describe hpa web-app-hpa
# 查看最近伸缩事件
kubectl get events --field-selector reason=ScheduledNoScaleDecision
# 查看HPA相关事件
kubectl get events --sort-by='.lastTimestamp' | grep hpa
常见问题排查:如果HPA显示desired replicas与current replicas不一致但不执行伸缩,检查是否到达稳定窗口期。如果显示unable to fetch metrics,检查Metrics Server状态和网络连通性。如果自定义指标HPA不工作,确认Prometheus Adapter的seriesQuery规则正确,使用kubectl get --raw验证指标是否可查。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/kubernetes-rong-qi-bian-pai-hpa-yu-vpa-zi-dong-shen-suo-shi/