第4章 自定义指标与HPA
上一章我们把Prometheus搭起来了,监控数据也有了。但说实话,光看监控面板没什么意思,真正的价值在于让系统自己动起来。这一章咱们聊聊怎么用Prometheus Adapter把自定义指标暴露给HPA,实现真正基于业务负载的自动扩缩容。
为什么默认的HPA不够用?
K8s自带的HPA默认支持CPU和内存指标,这俩指标够用吗?分场景。我见过不少团队,线上服务CPU使用率常年不到10%,但QPS已经快把服务压垮了。为啥?因为你的服务是IO密集型的,瓶颈在数据库连接、在外部API调用,而不是CPU计算。
还有更典型的场景:你的服务是消息消费者,消费速度取决于队列长度。CPU和内存看着都正常,但积压的消息越来越多。这时候按CPU扩缩容,根本反应不过来。
所以,我们需要把业务指标暴露给HPA。比如:
- 每秒请求数(QPS)
- P99延迟
- 队列积压量
- 活跃连接数
核心思路:应用暴露指标 → Prometheus采集 → Prometheus Adapter转换 → HPA获取指标 → 调整副本数
说白了,Prometheus Adapter就是一座桥,把Prometheus里的数据翻译成HPA能理解的格式。K8s的HPA只认metrics.k8s.io和custom.metrics.k8s.ioAPI,Prometheus的数据格式它看不懂。
整体架构一览
先看一张图,把整个链路串起来:
第一步:应用暴露业务指标
你得先让应用把QPS和延迟暴露出来。这里我用一个简单的Go应用做示例,用Prometheus客户端库暴露指标:
// main.go
package main
import (
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
// 定义QPS计数器
httpRequests = promauto.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total HTTP requests",
},
[]string{"path"},
)
// 定义延迟直方图
httpDuration = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request duration",
Buckets: []float64{0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0},
},
[]string{"path"},
)
)
func handler(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// 模拟业务处理
time.Sleep(time.Duration(50+time.Now().UnixNano()%100) * time.Millisecond)
w.Write([]byte("OK"))
// 记录指标
httpRequests.WithLabelValues(r.URL.Path).Inc()
httpDuration.WithLabelValues(r.URL.Path).Observe(time.Since(start).Seconds())
}
func main() {
// 注册Prometheus指标端点
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/api/v1/data", handler)
http.ListenAndServe(":8080", nil)
}
注意几个关键点:
- Counter类型适合计数,比如总请求数
- Histogram适合记录延迟分布,配合
histogram_quantile可以算P99 /metrics端点必须独立于业务接口,别和业务路由混在一起
我的建议:别把所有路径混在一个指标里。后续你要按路径维度做不同扩缩容策略的话,现在分好label能省很多事。
第二步:安装和配置Prometheus Adapter
Adapter的安装不难,用Helm一把梭:
# values.yaml
prometheus:
url: http://prometheus.monitoring.svc:9090
rules:
default: false
custom:
- seriesQuery: 'http_requests_total{namespace!="",pod!=""}'
resources:
overrides:
namespace: {resource: "namespace"}
pod: {resource: "pod"}
name:
matches: "^(.*)_total"
as: "${1}_qps"
metricsQuery: |
sum(
rate(<<.Series>>{<<.LabelMatchers>>}[1m])
) by (<<.GroupBy>>)
- seriesQuery: 'http_request_duration_seconds_bucket{namespace!="",pod!=""}'
resources:
overrides:
namespace: {resource: "namespace"}
pod: {resource: "pod"}
name:
as: "http_request_duration_p99"
metricsQuery: |
histogram_quantile(0.99,
sum(rate(<<.Series>>{<<.LabelMatchers>>}[5m])) by (le, <<.GroupBy>>)
)
这段配置看起来有点绕,我给你拆开讲讲:
seriesQuery:告诉Adapter去Prometheus里查什么序列resources.overrides:把标签映射到K8s资源,这样HPA才能关联到Podname.matches/as:指标名转换,把http_requests_total转成http_requests_qpsmetricsQuery:PromQL查询模板,<<Series>>和<<LabelMatchers>>是模板变量
我曾经踩过的坑:resources.overrides必须写对。如果你漏了namespace映射,Adapter会报错找不到资源。这个错还特别隐蔽,日志里只会显示"unable to get metric"。
安装命令:
helm install prometheus-adapter prometheus-community/prometheus-adapter -f values.yaml -n monitoring
第三步:验证Adapter是否正常工作
装完别急着写HPA,先验证一下Adapter有没有把指标暴露出来:
# 查看APIService是否注册
kubectl get apiservice | grep custom.metrics
# 直接查询指标
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1" | jq
# 查询具体的Pod指标
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/namespaces/default/pods/*/http_requests_qps" | jq
如果返回值正常,你会看到类似这样的结果:
{
"kind": "MetricValueList",
"apiVersion": "custom.metrics.k8s.io/v1beta1",
"metadata": {},
"items": [
{
"describedObject": {
"kind": "Pod",
"name": "app-6b4f9f5d8c-abc12",
"namespace": "default"
},
"metric": {
"name": "http_requests_qps",
"selector": null
},
"timestamp": "2024-01-15T10:30:00Z",
"value": "250m"
}
]
}
注意那个250m,这是K8s的量化格式,表示0.25。意思是这个Pod当前的QPS是0.25。嗯,测试环境嘛,流量小很正常。
第四步:编写HPA配置
指标通了,HPA就好写了。这里我写两个HPA,一个按QPS,一个按延迟:
# hpa-qps.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: app-qps-hpa
namespace: default
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 3
maxReplicas: 20
behavior:
scaleDown:
stabilizationWindowSeconds: 300 # 缩容冷静期
policies:
- type: Percent
value: 20
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 30 # 扩容要快
policies:
- type: Pods
value: 4
periodSeconds: 30
metrics:
- type: Object
object:
metric:
name: http_requests_qps
describedObject:
apiVersion: v1
kind: Service
name: my-app
target:
type: AverageValue
averageValue: 100 # 每个Pod目标100 QPS
再来一个基于延迟的:
# hpa-latency.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: app-latency-hpa
namespace: default
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 3
maxReplicas: 20
metrics:
- type: Pods
pods:
metric:
name: http_request_duration_p99
target:
type: AverageValue
averageValue: 500m # P99延迟目标500ms
这里有个设计取舍,我想提一下。QPS和延迟两个HPA同时挂同一个Deployment上,K8s会取两者期望副本数的最大值来扩容,但缩容时取最小值。这个机制其实挺合理的,任何一项指标超标都扩容,但都要降下来才缩容。
生产环境建议:HPA的behavior字段一定要配置。我见过太多事故是因为扩容太慢导致流量冲垮服务,或者缩容太快引发抖动。
进阶:多指标组合策略
刚才那种双HPA的方式有个问题——两个HPA互相不感知,逻辑上总感觉不够优雅。K8s其实支持在同一个HPA里配置多个指标:
# hpa-combined.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: app-combined-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 3
maxReplicas: 20
metrics:
- type: Pods
pods:
metric:
name: http_requests_qps
target:
type: AverageValue
averageValue: 100
- type: Pods
pods:
metric:
name: http_request_duration_p99
target:
type: AverageValue
averageValue: 500m
K8s会计算每个指标对应的期望副本数,取最大值执行扩容。这样做的好处是配置集中,便于查看和管理。
调试HPA:性能问题排查
我估计你迟早会遇到HPA不生效的坑。别急,惯用套路先走一遍:
# 看HPA状态
kubectl describe hpa app-qps-hpa
# 看Adapter日志
kubectl logs -n monitoring deploy/prometheus-adapter --tail=50
# 看HPA实际拿到的指标值
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/namespaces/default/pods/*/http_requests_qps" | jq '.items[].value'
常见的坑无非这几种:
| 现象 | 可能原因 | 排查方法 |
|---|---|---|
| HPA显示<unknown> | Adapter没找到指标或资源映射错误 | 检查Adapter配置和日志 |
| 指标值一直为0 | PromQL查询问题或标签不匹配 | 直接在Prometheus里跑一下查询 |
| 扩缩容反应慢 | Prometheus采集间隔或HPA同步周期长 | 调整scrape_interval和HPA的--horizontal-pod-autoscaler-sync-period |
| 频繁抖动 | 缺少稳定窗口或阈值过小 | 调大stabilizationWindowSeconds |
还记得我之前说的那件事吗?曾经有个线上服务频繁扩容缩容,我排查了一下午,最后发现是Prometheus的rate()窗口太短,导致QPS计算波动特别大。把1m改成5m的rate窗口,世界立刻清净了。
一个完整的落地案例
最后我写一个生产级别的完整示例。假设我有一个网关服务,要求:
- QPS超过500就扩容
- P99延迟超过300ms也扩容
- 扩容要快(30秒内加2个副本),缩容要慢(5分钟稳定窗口)
- 最大20个副本,最小3个
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: gateway-hpa
namespace: prod
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: api-gateway
minReplicas: 3
maxReplicas: 20
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Pods
value: 4
periodSeconds: 15
- type: Percent
value: 100
periodSeconds: 15
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Pods
value: 1
periodSeconds: 60
metrics:
- type: Pods
pods:
metric:
name: http_requests_qps
target:
type: AverageValue
averageValue: 500
- type: Pods
pods:
metric:
name: http_request_duration_p99
target:
type: AverageValue
averageValue: 300m
配置看起来简单,但这背后我踩过不少坑。稳定窗口这个参数,我建议你别照搬别人的数字。每个业务的流量模型不一样,有的白天高峰晚上低谷,有的突发性强。你需要用监控数据去反推合适的参数。
到底该用QPS还是延迟?
我看到好多团队在这个问题上纠结。我的看法:
- QPS适合业务型扩容——你想维持每个Pod的负载水平,对水平扩展有明确预期
- 延迟适合服务型扩容——你不太关心QPS,只关心用户体验,延迟超标就扩容
说实话,两个一起用最靠谱。QPS保证吞吐量,延迟兜底,防止漏网之鱼。
但你要注意,基于延迟扩容有个坑——延迟是滞后指标。流量突然暴涨时,延迟可能还没反应过来,服务已经超载了。所以我个人习惯是:QPS作为主指标,延迟作为兜底。
嗯,最后提醒一句:HPA不是万能的。它解决的是水平扩展的问题,如果你的服务有状态,扩容了也没用。那种场景你需要的是别的方案,比如分片或者消息队列削峰。但那是另外一个话题了。