HPA工作原理与指标数据链路
HPA(HorizontalPodAutoscaler)是Kubernetes内置的自动扩缩容组件,按Pod的指标使用率自动增减副本数。数据链路是:metrics-server采集节点与Pod的CPU内存指标,HPA控制器周期性拉取,计算当前副本数与目标值的比值,再调用ReplicaSet调整副本。
Kubernetes 1.23以上默认使用autoscaling/v2 API,支持多指标与自定义扩缩行为。先确认集群安装了metrics-server,否则CPU指标无法采集,HPA会一直处于unknown状态。
# 确认metrics-server运行
kubectl top nodes
kubectl top pods -n web
基于CPU内存指标的HPA最小配置
最小配置只用一个指标:targetAverageUtilization设为60,表示Pod平均CPU使用率超过60%时扩容,低于60%时缩容。默认冷却期300秒,避免指标波动引发副本抖动。
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-hpa
namespace: prod
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-server
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
多个指标同时配置时,HPA取扩缩需求最大的那个作为依据。CPU和内存一起监控,任何一个超限都触发扩容,避免单指标失真漏掉瓶颈。
自定义业务指标接入Prometheus Adapter
CPU内存指标无法反映队列积压、请求延迟等业务水位,需要把自定义指标接入HPA。Prometheus Adapter把Prometheus中的指标暴露给custom.metrics.k8s.io,再用Pods类型指标查询。
# prometheus-adapter 规则示例
rules:
- seriesQuery: 'http_requests_total{namespace!="",pod!=""}'
resources:
overrides:
namespace: {resource: "namespace"}
pod: {resource: "pod"}
metricsQuery: 'sum(rate(<<.Series>>{<<.LabelMatchers>>}[2m])) by (<<.GroupBy>>)'
配置后用kubectl get –raw验证指标是否可见。指标可用后,在HPA的metrics里加type: Pods,pods.metric.name填指标名,target.averageValue按单副本可承载的每秒请求数设置。
扩缩容边界行为与冷却时间优化
默认300秒冷静时间在流量陡增时拖慢扩容,流量回落后又延长缩容窗口,造成资源浪费。autoscaling/v2支持behavior字段精细控制扩缩容的速率和窗口。
behavior:
scaleUp:
stabilizationWindowSeconds: 60
policies:
- type: Percent
value: 100
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Pods
value: 1
periodSeconds: 60
scaleUp阶段每60秒最多翻倍,适应爆发流量;scaleDown阶段每60秒只缩1个副本,并保留5分钟稳定窗口,避免短时抖动被快速回收。需要预留buffer可以在maxReplicas多留20%余量。
HPA监控、限流与故障排查
上线后kubectl describe hpa查看当前副本数与计算过程。常见故障:指标unknown(metrics-server未装)、扩容不生效(Pod未配resource requests)、副本抖动(稳定窗口太短)。Pod的limits与下游数据库连接池容量要一起规划,扩到上限仍扛不住,问题就在下游链路。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/kuberneteshpa-tan-xing-kuo-suo-rong-pei-zhi-shi-zhan-zhi/