K8s HPA 弹性伸缩进阶:基于自定义指标(Pod CPU 使用率 + QPS)的扩缩容配置
·
Kubernetes HPA 进阶:基于 CPU 使用率与 QPS 的弹性伸缩配置
Kubernetes HPA(Horizontal Pod Autoscaler)支持基于自定义指标实现精细化的弹性伸缩。以下结合 Pod CPU 使用率 和 QPS(每秒请求数) 的配置方案,实现双指标驱动的扩缩容策略。
核心组件依赖
-
Metrics Server
提供基础资源指标(如 CPU/Memory):kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml -
Prometheus + Adapter
收集/暴露自定义指标(如 QPS):# prometheus-adapter 配置片段 rules: - seriesQuery: 'http_requests_total{namespace!="",pod!=""}' resources: { overrides: { pod: { resource: "pod" } } } name: { matches: ".*", as: "http_requests_per_second" } metricsQuery: 'sum(rate(<<.Series>>{<<.LabelMatchers>>}[2m])) by (<<.GroupBy>>)'
HPA 双指标配置
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: qps-cpu-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-webapp
minReplicas: 2
maxReplicas: 20
metrics:
# 指标1:CPU 使用率(资源类型)
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60 # 目标 CPU 使用率 60%
# 指标2:QPS(Pods 类型自定义指标)
- type: Pods
pods:
metric:
name: http_requests_per_second # Prometheus Adapter 暴露的指标名
target:
type: AverageValue
averageValue: 100 # 目标:每个 Pod 平均每秒处理 100 个请求
关键配置解析
-
指标优先级逻辑
HPA 会独立计算每个指标的期望副本数,最终取 最大值 作为实际扩缩容目标。例如:- CPU 指标建议扩容至 5 个 Pod
- QPS 指标建议扩容至 8 个 Pod
- 最终执行:扩容至 8 个 Pod
-
QPS 指标采集原理
- 应用需暴露请求计数器(如
http_requests_total) - Prometheus 通过
rate()函数计算每秒请求率: $$ \text{QPS} = \frac{\Delta \text{request_count}}{\Delta t} $$ - Adapter 将指标转换为 Kubernetes 可识别的格式
- 应用需暴露请求计数器(如
-
扩缩容行为调优(可选)
添加behavior配置避免抖动:behavior: scaleDown: stabilizationWindowSeconds: 300 # 缩容冷却窗口 5 分钟 policies: [{ type: Percent, value: 10, periodSeconds: 60 }] # 每分钟最多缩容 10%
验证与调试
-
检查指标可用性:
kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1 | jq -
实时监控 HPA 决策:
kubectl describe hpa qps-cpu-hpa输出关键事件:
Metrics: ( current / target ) "http_requests_per_second" on pods: 150 / 100 "cpu" on pods: 75% / 60%
最佳实践
-
指标权重调整
若需优先保障服务吞吐量,可设置更高的 QPS 目标值;若需控制资源成本,则降低 CPU 目标阈值。 -
异常保护机制
- 配置
minReplicas防止服务不可用 - 使用 PodDisruptionBudget 保障更新时最小可用副本数
- 配置
-
多维度监控
结合 Grafana 仪表盘监控核心指标:- Pod CPU 使用率 $$ \frac{\text{CPU_used}}{\text{CPU_limit}} \times 100% $$
- 集群总 QPS:$$ \sum_{i=1}^{n} \text{QPS}_i $$
注:实际部署时需根据应用特性调整目标阈值,并通过压力测试验证伸缩边界。
更多推荐

所有评论(0)