HPA工作原理与控制循环机制
Kubernetes HPA(Horizontal Pod Autoscaler)根据监控指标自动调整Pod副本数量,是容器编排平台实现弹性伸缩的核心能力。在流量波动剧烈的业务场景中,HPA能在高峰期自动扩容保证响应延迟,低峰期自动缩容节省计算资源。本文从HPA工作机制出发,覆盖CPU/内存指标配置、自定义指标接入、缩容策略调优和常见问题排查。
HPA Controller以固定间隔(默认15秒)从Metrics Server拉取Pod指标,计算当前指标与目标值的比值,据此调整Deployment的replicas字段。计算公式为:期望副本数 = ceil(当前副本数 × (当前指标值 / 目标指标值))。
HPA支持三种指标类型:Resource指标(CPU、内存)、Pod自定义指标和外部指标。Resource指标通过Metrics Server采集,部署在集群内的metrics-server Pod从各节点的kubelet cAdvisor获取容器指标。自定义指标和外部指标需要通过API Aggregation层注册的自定义指标API服务暴露。
# 安装Metrics Server
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
# 验证指标采集
kubectl top nodes
kubectl top pods -n default
基于CPU利用率的HPA基础配置
CPU利用率是最常用的伸缩指标。HPA根据Pod的CPU使用率与目标值的比值计算期望副本数。配置HPA前,Deployment必须定义resources.requests.cpu,否则HPA无法计算百分比。
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-api
spec:
replicas: 3
template:
spec:
containers:
- name: api
image: registry.example.com/web-api:v2.1
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-api-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-api
minReplicas: 3
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 30
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50
periodSeconds: 60
minReplicas设为3保证最低可用性,maxReplicas限制最大资源消耗。averageUtilization设为70表示CPU使用率超过70%触发扩容。behavior字段是autoscaling/v2版本的增强能力,分别控制扩容和缩容行为。
自定义指标接入与Prometheus Adapter配置
CPU指标无法反映业务真实负载。对于QPS驱动的服务,需要基于每秒请求数伸缩。Prometheus Adapter将Prometheus中的自定义指标暴露为Kubernetes Metrics API,供HPA消费。
# Prometheus Adapter规则配置
apiVersion: v1
kind: ConfigMap
metadata:
name: prometheus-adapter
namespace: monitoring
data:
config.yaml: |
rules:
- seriesQuery: 'http_requests_total{namespace!="",pod!=""}'
resources:
overrides:
namespace: {resource: "namespace"}
pod: {resource: "pod"}
name:
matches: "^(.*)_total"
as: "${1}_per_second"
metricsQuery: 'sum(rate(<<.Series>>{<<.LabelMatchers>>}[2m])) by (<<.GroupBy>>)'
seriesQuery定义Prometheus中的原始指标,metricsQuery通过rate()函数将计数器转换为每秒速率。配置完成后,通过kubectl获取自定义指标:
# 查询自定义指标
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/namespaces/default/pods/*/http_requests_per_second"
HPA配置中引用该自定义指标:
metrics:
- type: Pods
pods:
metric:
name: http_requests_per_second
target:
type: AverageValue
averageValue: "100"
averageValue设为100表示每个Pod平均每秒处理100个请求时维持现状,超过则扩容。AverageValue模式比Utilization模式更直观,直接表达业务SLA目标。
多指标组合与缩容保护策略
HPA支持同时配置多个指标,取各指标计算结果的较大值作为期望副本数。这种策略保证任何一个指标过载都会触发扩容,而缩容需要所有指标都低于阈值。
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
- type: Pods
pods:
metric:
name: http_requests_per_second
target:
type: AverageValue
averageValue: "100"
缩容保护是HPA调优的重点。默认配置下HPA缩容过快可能导致流量波动时服务雪崩。behavior.scaleDown的stabilizationWindowSeconds设为300秒(5分钟),表示连续5分钟指标都低于阈值才开始缩容。缩容策略的Percent value设为50,每次最多缩减当前副本数的50%,避免一次缩容幅度过大。
behavior:
scaleDown:
stabilizationWindowSeconds: 300
selectPolicy: Max
policies:
- type: Percent
value: 50
periodSeconds: 60
- type: Pods
value: 4
periodSeconds: 60
selectPolicy: Max取多个策略中较保守的结果。上述配置同时定义了百分比策略(最多缩50%)和绝对值策略(最多缩4个Pod),取两者中缩减较小的值执行。
KEDA事件驱动伸缩与HPA对比
KEDA(Kubernetes Event-Driven Autoscaling)建立在HPA之上,扩展了指标来源,支持Kafka、RabbitMQ、Redis Stream、Azure Service Bus等事件源触发伸缩。对于消息队列消费者场景,KEDA能根据积压消息数精确伸缩Worker数量,并在无消息时缩容到零。
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: kafka-consumer
namespace: default
spec:
scaleTargetRef:
name: kafka-worker
minReplicaCount: 0
maxReplicaCount: 30
pollingInterval: 30
cooldownPeriod: 300
triggers:
- type: kafka
metadata:
bootstrapServers: kafka.kafka:9092
consumerGroup: order-processing
topic: orders
lagThreshold: "100"
lagThreshold设为100,表示每个分区消息积压超过100条触发扩容。minReplicaCount设为0实现scale-to-zero,无消息时释放全部计算资源。cooldownPeriod控制缩容到零前的等待时间。
HPA常见问题排查
HPA配置后指标不生效是最高频的问题。排查步骤如下:
# 查看HPA状态和指标
kubectl describe hpa web-api-hpa
# 常见错误1: Metrics Server未就绪
# 现象: "the HPA was unable to compute the replica count"
# 排查: kubectl top pods 验证指标采集是否正常
# 常见错误2: 缺少resources.requests
# 现象: "missing request for cpu"
# 排查: kubectl get deployment -o yaml | grep -A5 resources
# 常见错误3: 自定义指标API未注册
# 现象: "unable to fetch metrics from custom.metrics.k8s.io"
# 排查: kubectl get apiservice | grep custom.metrics
# 查看HPA事件
kubectl get events --field-selector involvedObject.name=web-api-hpa
HPA扩容抖动(频繁扩缩容)是另一个常见问题。现象是Pod数量在短时间反复波动。根因通常是stabilizationWindowSeconds设置过短或指标采集间隔过短。将缩容稳定窗口调至300秒以上,CPU指标采集周期调至60秒以上可有效缓解抖动。对于Prometheus Adapter场景,确保metricsQuery中的rate窗口(如[2m])足够长,平滑短时指标波动。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/kuberneteshpa-shui-ping-zi-dong-shen-suo-yu-zi-ding-yi-zhi/