Kubernetes 专题从第一个 Pod 到生产平台
总目录/第 13 章

Kubernetes 专题 · S3 看得见:可观测、发布与排障 · 第 13 / 26 章

13指标、扩缩与告警

30 秒速览:kubectl top 只答「此刻多少」。本章把它变成「过去一小时」和一条会自己响的告警:装 kube-prometheus-stack、抓指标、写 PromQL 算错误率与 P95、让 HPA 从 3 扩到 6,最后让一条规则真的 firing。

13.1 本章在哪

第 7 章你给 shop-api 加了 /healthz 和 /metrics,并装了 metrics-server,于是 kubectl top pod 能报出每个 Pod 的 CPU。但那份能力只够回答「现在多少」:高峰过后,它什么都不记得,也不会叫醒任何人。

位置内容
主线之前第 7 章装好的 metrics-server 与 shop-api 的 /metrics;第 12 章的日志管道
主线之后shop 里的 ServiceMonitor、HPA、PrometheusRule;platform 里的一整套 Prometheus 与 Alertmanager
本章产物platform/kube-prometheus-stack-values.yaml、deploy/metrics/ 下三个清单、改过的 apps/shop-api/main.go
适用环境kind 单集群,CPU 建议给到 6 核以上;Prometheus 与 Grafana 都是真实工作负载

13.2 学习目标

学完你能
  • 解释 ServiceMonitor、Service、Endpoints 如何匹配出一个抓取目标。
    判定标准:能说出「端口名写错」会让 target 消失在哪一步。
  • 用 PromQL 写出错误率与 P95,并说明窗口的取舍。
    判定标准:换个窗口,你能说出曲线会变钝还是变尖。
  • 让 HPA 稳定扩容,并说清它为什么不扩容。
    判定标准:看到 TARGETS 85%/99% 能算出期望副本数。
  • 让一条告警从表达式走到 Alertmanager,并定位断点。
    判定标准:会查 /api/v1/alertmanagers 与 /api/v1/rules。

13.3 场景

周五晚上八点,一场投放把 shop.example.com 的流量推到平时四倍。shop-api 三个副本 CPU 全部贴着 limit 跑,请求排队,超时后网关返回 502,应用自己吐 500。没有人收到通知:告警群最后一条消息是三个月前的。

周六上午十点,有人翻 Grafana 才发现:昨天 20:00 到 21:30,5xx 比例最高到过 12%,持续近二十分钟。复盘时最刺人的一句是「不是监控没报,是我们根本没有监控」。

你现有的工具是 kubectl top:采样点,不留历史,没阈值,没有通知渠道。本章补上四件事:指标被采集、被计算、被扩缩用、异常被人知道。任何一环断掉,后面全是摆设。

13.4 心智模型

把本章想成两条并行的链路,见图 1。上面是「指标链」:应用暴露 /metrics,ServiceMonitor 描述怎么抓,Prometheus 拉取存储,PrometheusRule 周期求值,结果推给 Alertmanager 路由。下面是「扩缩链」:metrics-server 定期问 kubelet 要用量,HPA 读它算期望副本,最后改 Deployment 的 replicas。

指标链:一次抓取到一次通知 shop-api :8080/metrics ServiceMonitor 怎么抓 Prometheus 拉取并存储 PrometheusRule 周期性求值 Alertmanager 路由与分组 扩缩链:一次采样到一个新副本 metrics-server 15s 聚合一次 HPA 算期望副本 Deployment replicas 3 → 6 同一个 Deployment
图 1 ·两条链路只在 shop-api 这个对象上相交,其余环节互不知情。

两条链的交点只有 shop-api:上面一条看它的输出,下面一条改它的副本数。所以先把指标做成能算错误率的样子,再谈扩缩和告警——维度不对,后面的 PromQL 与规则全是空转。

常见误解实际是什么
有了 metrics-server 就有监控它只保留最近十几分钟的资源用量,没有历史、没有查询语言、没有告警,副本一重建数据就断
HPA 看的是节点的 CPU看的是 Pod 的 requests.cpu 占比,没有 requests 的 Pod 在它眼里是 <unknown>
告警是 Prometheus 发出去的Prometheus 只负责在阈值上停留够久后置为 firing,发不发、发给谁由 Alertmanager 的 route 决定

13.5 概念与字段速查

对象 / 字段作用默认值生产建议
ServiceMonitor spec.endpoints[].port指定抓哪个端口,值必须是 Service 里的端口名无,必填给端口起有意义的名字,如 http-metrics
ServiceMonitor spec.endpoints[].interval抓取周期跟随 Prometheus 的 scrapeInterval,30s核心服务 15s,边缘服务 60s
Prometheus serviceMonitorSelectorNilUsesHelmValues为真时只选带 release 标签的 ServiceMonitortrue置 false,或给自建对象补 release 标签
Prometheus ruleSelectorNilUsesHelmValues同上,作用于 PrometheusRuletrue与上一行保持一致
Prometheus retention本地 TSDB 保留时长10d按磁盘与查询需求定,长留存下沉到远端存储
PrometheusRule spec.groups[].rules[].for表达式连续为真多久才 firing0s至少覆盖两个求值周期,避免抖动
HorizontalPodAutoscaler averageUtilization目标 CPU 利用率,按 requests 计算无,资源型指标必填60–80,留出突发余量
metrics-server --metric-resolution采集间隔,决定 HPA 的反应速度15s保持默认,改小只会增加 apiserver 压力
可跳过 · HPA 的期望副本数是怎么算出来的

资源型指标的公式是 期望副本 = ceil(当前副本 × 当前利用率 / 目标利用率),结果夹在 min 与 max 之间。利用率的分母是就绪 Pod 的 requests 之和,不是 limit——把 limit 调大不会更早扩容。

一句话:ServiceMonitor 决定抓不抓得到,PromQL 决定算不算得对,HPA 只信 requests。

13.6 动手

先交代本章唯一要改的应用代码。第 7 章给 shop-api 的 /metrics 只有一个计数器 shop_api_requests_total,没有 status 标签:它算得出 QPS,算不出错误率。为了让 PromQL 与生产里的通用写法对齐,这里扩一次指标:

关注点改动前(第 7 章)改动后(本章)为什么
指标名shop_api_requests_totalhttp_requests_total去掉应用前缀,换成社区通用的命名,表达式可以原样搬到别的服务
标签无status="200" status="500"错误率需要分子,靠标签才拆得开
耗时无http_request_duration_seconds_bucketP95 只能从直方图的桶里算,平均值给不出尾部
抓取副作用抓一次 /metrics 也计数抓取与业务分开统计否则抓取频率会污染错误率的分母
演练入口无/fail 返回 500造 5xx 不需要真的弄坏数据库

Step 1 · 校验第 12 章留下的现场

意图确认三个副本都在、metrics-server 仍健康。

# env: all
cd ~/work/aurora-shop
make verify-ch12
kubectl -n shop get deploy shop-api
kubectl -n kube-system get deploy metrics-server

预期输出:make verify-ch12 打印 ok 并退出 0;shop-api 是 3/3,metrics-server 是 1/1;kubectl top pod -n shop 返回数字。

不一致怎么办:kubectl top 报错时先看 kubectl -n kube-system get apiservice v1beta1.metrics.k8s.io 的 AVAILABLE 列。它是 False 时本章的负向现象会提前出现,先修它。

Step 2 · 把 /metrics 改成能算错误率的样子

意图给计数器加 status 标签,补一个耗时直方图,再开一个只用于演练的 /fail 端点。

// file: apps/shop-api/main.go(改动后:状态码维度 + 直方图 + /fail)
var (
	metricsMu sync.Mutex
	byStatus  = map[string]float64{}
	leList    = []float64{0.05, 0.1, 0.25, 0.5, 1, 2.5, 5}
	cumBucket = map[float64]float64{}
	durSum    float64
	durCount  float64
)

func observe(status string, d time.Duration) {
	metricsMu.Lock()
	defer metricsMu.Unlock()
	byStatus[status]++
	durSum += d.Seconds()
	durCount++
	for _, le := range leList {
		if d.Seconds() <= le {
			cumBucket[le]++
		}
	}
}

type recorder struct {
	http.ResponseWriter
	code int
}

func (r *recorder) WriteHeader(code int) {
	r.code = code
	r.ResponseWriter.WriteHeader(code)
}

func withMetrics(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rw := &recorder{ResponseWriter: w, code: 200}
		start := time.Now()
		next.ServeHTTP(rw, r)
		observe(strconv.Itoa(rw.code), time.Since(start))
	})
}

func metricsHandler(w http.ResponseWriter, r *http.Request) {
	metricsMu.Lock()
	defer metricsMu.Unlock()
	w.Header().Set("Content-Type", "text/plain; version=0.0.4")
	fmt.Fprint(w, "# TYPE http_requests_total counter\n")
	for _, s := range []string{"200", "404", "500"} {
		fmt.Fprintf(w, "http_requests_total{status=%q} %g\n", s, byStatus[s])
	}
	fmt.Fprint(w, "# TYPE http_request_duration_seconds histogram\n")
	for _, le := range leList {
		fmt.Fprintf(w, "http_request_duration_seconds_bucket{le=%q} %g\n",
			strconv.FormatFloat(le, 'g', -1, 64), cumBucket[le])
	}
	fmt.Fprintf(w, "http_request_duration_seconds_bucket{le=\"+Inf\"} %g\n", durCount)
	fmt.Fprintf(w, "http_request_duration_seconds_sum %g\n", durSum)
	fmt.Fprintf(w, "http_request_duration_seconds_count %g\n", durCount)
}

func failHandler(w http.ResponseWriter, r *http.Request) {
	// 演练用:稳定返回 500,不退出、不重启
	http.Error(w, "injected failure", http.StatusInternalServerError)
}

// 注册:/metrics 不包 withMetrics,否则每次抓取都会进分母
mux.HandleFunc("/metrics", metricsHandler)
mux.Handle("/fail", withMetrics(http.HandlerFunc(failHandler)))
mux.Handle("/", withMetrics(appMux))

withMetrics 用 WriteHeader 截住状态码,所以 500 是应用自己产生的;recorder 默认记 200。

# env: all
make image
make load
kubectl -n shop rollout restart deploy/shop-api
kubectl -n shop rollout status deploy/shop-api --timeout=90s
kubectl -n shop exec deploy/shop-api -- curl -s localhost:8080/metrics | head -n 5

预期输出:rollout status 打印 deployment "shop-api" successfully rolled out;curl 的前几行是新的指标名。

# 预期输出
# TYPE http_requests_total counter
http_requests_total{status="200"} 3
http_requests_total{status="404"} 0
http_requests_total{status="500"} 0
# TYPE http_request_duration_seconds histogram

不一致怎么办:还是旧指标名说明 Pod 没换镜像,看 Image ID。

Windows 11 + WSL2

make image 调用的 docker 可能来自 Docker Desktop。跑 docker context show,看到 desktop-linux 说明镜像建在虚拟机里,kind load 仍取得到。

Linux (Ubuntu 24.04)

docker 就是本机的 dockerd,systemctl is-active docker 返回 active 即可。kind load 直接从本地镜像库读,没有额外的层要同步。

差异结论:命令完全一样,差别只在镜像由谁构建。WSL 报 Cannot connect to the Docker daemon 时先确认 Docker Desktop 已启动,别去改 Makefile。

易错点 · 指标改了,抓到的还是旧数字

现象:curl /metrics 已经有 http_requests_total,但 Prometheus 里查不到这个指标名。

原因:make load 只把镜像推进节点,Pod 仍跑着旧镜像;或者 rollout 完成但 Prometheus 还没到下一个抓取周期。

怎么验证:kubectl -n shop get pod -o jsonpath='{.items[0].status.containerStatuses[0].imageID}' 与 docker images --digests 对一下摘要,再等一个 interval。

Step 3 · 把 kube-prometheus-stack 装进 platform

意图装上 Prometheus、Alertmanager、Grafana 与 Operator 四件套,并把选择器改成「认所有 ServiceMonitor」。

# env: all
cat > platform/kube-prometheus-stack-values.yaml <<'EOF'
grafana:
  enabled: true
prometheus:
  prometheusSpec:
    retention: 6h
    serviceMonitorSelectorNilUsesHelmValues: false
    ruleSelectorNilUsesHelmValues: false
EOF
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm upgrade --install kps prometheus-community/kube-prometheus-stack \
  --version 93.2.0 \
  --namespace platform --create-namespace \
  -f platform/kube-prometheus-stack-values.yaml \
  --wait --timeout 10m

预期输出:STATUS: deployed,随后 kubectl -n platform get pod 里 Operator、Prometheus、Alertmanager、Grafana 四个 Pod 全是 Running;get prometheus 的 AVAILABLE 为 1/1。

不一致怎么办:--wait 超时多半是镜像还在拉,看 ImagePullBackOff。

两个 *SelectorNilUsesHelmValues: false 是本章的关键开关。它们为 true 时 Operator 只收带 release: kps 标签的对象,你新建的 ServiceMonitor 会被静默忽略——不报错,也不抓。

Step 4 · 用一个 ServiceMonitor 抓到 shop-api

意图让 Prometheus 认领 shop-api 的 /metrics,并确认三个副本各产生一个 target。

# file: deploy/metrics/shop-api-servicemonitor.yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: shop-api
  namespace: shop
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: shop-api
  endpoints:
    - port: http
      path: /metrics
      interval: 15s
  namespaceSelector:
    matchNames:
      - shop

图 2 的三处匹配里,endpoints[].port 只认端口名;写数字时 Operator 匹配不到,直接在生成的配置里跳过这条,不报错。

ServiceMonitor spec.selector.matchLabels Service metadata.labels + spec.ports[].name Endpoints 真实 Pod IP 与端口号 Prometheus 生成 一个 target 标签 job=shop-api up == 1 才算抓成功 每个副本一条
图 2 ·三处匹配任何一处不成立,target 就不会出现;出现但 up 为 0 则是网络或路径问题。
# env: all
kubectl -n shop get svc shop-api -o jsonpath='{.spec.ports[*].name}'; echo
kubectl apply -f deploy/metrics/shop-api-servicemonitor.yaml
kubectl -n platform port-forward svc/kps-kube-prometheus-stack-prometheus 9090:9090 &
sleep 3
curl -s 'localhost:9090/api/v1/targets?state=active' \
  | jq -r '.data.activeTargets[] | select(.labels.job=="shop-api") | [.health,.scrapeUrl] | @tsv'

预期输出:端口名是 http,三行 up,各指向一个 Pod IP 的 8080。

# 预期输出
http
up	http://10.244.1.7:8080/metrics
up	http://10.244.2.4:8080/metrics
up	http://10.244.3.9:8080/metrics

不一致怎么办:按故障 1 的两步查配置与端口名。

Step 5 · 四条 PromQL,把「此刻」变成「趋势」

意图用四个查询回答四个问题:抓到了吗、量多大、错多少、慢不慢。

# env: all
q() { curl -sG localhost:9090/api/v1/query --data-urlencode "query=$1" \
      | jq -r '.data.result[] | "\(.metric.status // "all") \(.value[1])"'; }
q 'count(up{job="shop-api"} == 1)'
q 'sum(rate(http_requests_total[2m]))'
q 'sum(rate(http_requests_total{status=~"5.."}[2m])) / sum(rate(http_requests_total[2m]))'
q 'histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))'

预期输出:第一行健康副本数,第二行 QPS,第三行错误率,第四行 P95 秒数。

# 预期输出
all 3
all 2.4133
all 0.0000
all 0.0412

不一致怎么办:结果为空说明样本不够,等一个抓取周期。

想回答的问题PromQL为什么这么写
几个副本在被抓count(up{job="shop-api"} == 1)up 是抓取元数据,不做过滤会把历史序列也算进去
每秒多少请求sum(rate(http_requests_total[2m]))计数器必须先 rate,直接对累计值求和无意义
错误率sum(rate(http_requests_total{status=~"5.."}[2m])) / sum(rate(http_requests_total[2m]))分子分母同窗口,且先分别 sum 再相除,避免分副本相除后取平均
P95 延迟histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))桶必须先按 le 聚合,否则算的是某个副本的分位数

窗口取 2 分钟:15 秒间隔下有 8 个样本,够平滑也不糊掉尖峰。P95 用 5 分钟,因为分位数对样本量更敏感。

Step 6 · 让 HPA 从 3 扩到 6

意图用 CPU 利用率做扩缩信号:先看到 TARGETS 有百分数,再用真实压力推到 6 个副本。

# file: deploy/metrics/shop-api-hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: shop-api
  namespace: shop
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: shop-api
  minReplicas: 3
  maxReplicas: 6
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
# env: all
kubectl apply -f deploy/metrics/shop-api-hpa.yaml
kubectl -n shop get hpa shop-api
for p in $(kubectl -n shop get pod -l app.kubernetes.io/name=shop-api -o name); do
  for i in 1 2; do
    kubectl -n shop exec "$p" -- sh -c 'while true; do curl -s localhost:8080/ >/dev/null; done' &
  done
done
sleep 180
kubectl -n shop get hpa shop-api
kubectl -n shop get deploy shop-api

预期输出:刚创建时 REPLICAS 是 3、TARGETS 是一个小百分数;压测三分钟后副本变成 6,利用率回落到 70% 上下。

# 预期输出
NAME       REFERENCE             TARGETS   MINPODS   MAXPODS   REPLICAS   AGE
shop-api   Deployment/shop-api   2%/70%    3         6         3          40s
NAME       REFERENCE             TARGETS    MINPODS   MAXPODS   REPLICAS   AGE
shop-api   Deployment/shop-api   214%/70%   3         6         6          4m12s
NAME       READY   UP-TO-DATE   AVAILABLE   AGE
shop-api   6/6     6            6           3d4h

不一致怎么办:TARGETS 是 <unknown> 就回到故障 2。

六个循环是每副本两个;kubectl exec deploy/… 只选一个 Pod。

意图反过来验证一次:把目标调高,看它为什么不动。

# env: all
jobs -p | xargs -r kill
kubectl -n shop patch hpa shop-api --type=merge \
  -p '{"spec":{"metrics":[{"type":"Resource","resource":{"name":"cpu","target":{"type":"Utilization","averageUtilization":99}}}]}}'
sleep 120
kubectl -n shop describe hpa shop-api | tail -n 8
# 预期输出
Events:
  Type    Reason             Age    From                       Message
  ----    ------             ----   ----                       -------
  Normal  SuccessfulRescale  3m11s  horizontal-pod-autoscaler  New size: 6; reason: cpu resource utilization (percentage of request) above target
  Normal  SuccessfulRescale  90s    horizontal-pod-autoscaler  New size: 3; reason: All metrics below target

一次扩一次缩。目标 99% 不是更容易触发,而是更晚触发:85% 利用率下 ceil(3 × 85 / 99) = 3,期望副本没变,它只在 Events 里写一句 All metrics below target。

易错点 · 压测还没停就改目标

现象:改成 99% 之后副本反而从 3 涨到 6,和预期相反。

原因:利用率仍高于 99%,ceil(3 × 2.14 / 0.99) = 7,被 max 夹到 6。目标只是分母,压力还在就还会扩。

怎么验证:看 TARGETS 左边那个数是否已落到 99 以下。

Step 7 · 让一条告警真的 firing 一次

意图写一条错误率规则,用 /fail 稳定制造 5xx,看它从 inactive 走到 pending 再到 firing,并在 Alertmanager 里查到同一条。

# file: deploy/metrics/shop-api-rules.yaml
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: shop-api-rules
  namespace: shop
spec:
  groups:
    - name: shop-api.rules
      rules:
        - alert: ShopApiHighErrorRate
          expr: |
            sum(rate(http_requests_total{status=~"5.."}[2m]))
              / sum(rate(http_requests_total[2m])) > 0.05
          for: 2m
          labels:
            severity: warning
            service: shop-api
          annotations:
            summary: "shop-api 5xx 比例超过 5%"
            description: "近 2 分钟错误率为 {{ $value | humanizePercentage }}。"

状态机见图 3。每次求值为真 pending 计时器走一格,连续为真满 for 才进 firing;中间有一次为假就回到 inactive。

inactive pending firing resolved 表达式为真 持续 for 表达式为假 pending 中途断掉也走这条路
图 3 ·Alertmanager 只看到 firing 与 resolved 两端,中间过程在 Prometheus 里。
# env: all
kubectl -n platform port-forward svc/kps-kube-prometheus-stack-prometheus 9090:9090 &
kubectl apply -f deploy/metrics/shop-api-rules.yaml
for p in $(kubectl -n shop get pod -l app.kubernetes.io/name=shop-api -o name); do
  kubectl -n shop exec "$p" -- sh -c 'while true; do curl -s localhost:8080/fail >/dev/null; sleep 0.2; done' &
done
sleep 150
curl -s localhost:9090/api/v1/rules | jq -r '.data.groups[].rules[] | select(.name=="ShopApiHighErrorRate") | [.state,.alerts[0].value] | @tsv'
curl -s localhost:9090/api/v1/alertmanagers | jq -r '.data.activeAlertmanagers[].url'

预期输出:for: 2m 走完后状态是 firing,值在 0.9 以上;第二行是 Alertmanager 的地址。刚 apply 时先显示 pending。

# 预期输出
firing	0.9773
http://kps-kube-prometheus-stack-alertmanager.platform.svc:9093/api/v2/alerts

不一致怎么办:一直 pending 说明期间有一次求值为假。

关于 /fail

这个端点只负责稳定产生 500。真实环境更常见的做法是把 DATABASE_URL 指向不存在的库,让 / 自己返回 500——那验证真实失败路径,/fail 验证告警链路,不要留在生产镜像里。

易错点 · 告警一直在 pending

现象:错误率明明已经 90% 以上,规则状态却停在 pending,或者刚 firing 又掉回 inactive。

原因:for: 2m 要求连续为真;压测循环被打断、Pod 重建、或窗口内样本不足都会让某次求值为假。

怎么验证:在 Prometheus 页面上直接把 expr 贴进查询框,看曲线在这两分钟里有没有掉到 0.05 以下。

Step 8 · 提交产物

意图把本章新增的四个文件和改动过的 main.go 一起提交,让第 14 章从干净的现场开始。

# env: all
git add apps/shop-api/main.go platform/kube-prometheus-stack-values.yaml deploy/metrics/
git commit -m "ch13: metrics, promql, hpa and alerting"
git status --short

预期输出:git status --short 无输出(工作区干净),提交信息一行。

不一致怎么办:还有残留文件就先看清路径,别把临时改动带进去。

13.7 验收

按顺序做完五条才算通过:前三条验配置,后两条验行为。只做完前三条的人,往往到第 14 章才发现告警从没响过。

  1. servicemonitor shop-api 存在,Prometheus 的 availableReplicas 为 1,/api/v1/targets 里三个 job="shop-api" 都是 up。
  2. HPA 的 TARGETS 是 N%/70%,不是 <unknown>/70%。
  3. 压测三分钟后 REPLICAS 从 3 到 6,停止压测后回落。
  4. kubectl -n shop get prometheusrule shop-api-rules 存在,/api/v1/rules 里能看到 ShopApiHighErrorRate。
  5. 打 /fail 两分钟后规则为 firing,activeAlertmanagers 非空。

把这五条固化成 make verify-ch13:查对象是否齐全,抓两个 API 校验 target 与规则,确认 TARGETS 带百分号。反向验证:把 port 改错,脚本必须在第 1 条失败。

一句话:验收要验「响过」,不是验「配了」。

13.8 故障实验室

故障 1 · ServiceMonitor 建了,Target 却不出现

注入:把 spec.endpoints[0].port 从 http patch 成不存在的 metrics。

症状:kubectl get servicemonitor 正常,describe 没有事件;target 列表里 job="shop-api" 直接消失,不是 down,是没有。

诊断:看 Operator 有没有把它写进配置。kubectl -n platform exec prometheus-kps-kube-prometheus-stack-prometheus-0 -c prometheus -- grep -c 'job_name: shop-api' /etc/prometheus/config_out/prometheus.env.yaml。输出 0 说明问题在选择器或标签,输出 1 说明在端口名。

根因:三处匹配(图 2)任一断裂。最常见的是端口名写错;其次是 serviceMonitorSelectorNilUsesHelmValues 仍为 true 而对象没带 release 标签。

修复:把 port 改回 http,一分钟后 target 回来。

预防:ServiceMonitor 与 Service 同目录评审,端口名不手写。

故障 2 · HPA 一直是 TARGETS <unknown>/70%

注入:删掉 Deployment 里的 resources.requests 整块。

症状:TARGETS 变成 <unknown>/70%,副本数停在 MINPODS,压力再大也不动。

诊断:kubectl -n shop describe hpa shop-api 的 Events 里有一行 failed to get cpu utilization: missing request for cpu。若换成 unable to fetch metrics from resource metrics API,那是 metrics-server 的问题,方向不同。

根因:利用率的分母是 requests 之和;没有 requests 就没有分母。HPA 拿不到指标时不会乐观扩容,只会停手。

修复:把 requests 加回去并确认滚动完成。

预防:准入层强制 requests,或用 LimitRange 给默认值。

故障 3 · 规则 firing 了,Alertmanager 却没收到

注入:把 Prometheus CR 的 alerting.alertmanagers[0].name 改成 alertmanager,而真实服务名带 kps-kube-prometheus-stack- 前缀。

症状:/api/v1/rules 里是 firing,Alertmanager 的 /api/v2/alerts 却是空数组,一条通知都没发。

诊断:curl -s localhost:9090/api/v1/alertmanagers | jq '.data.activeAlertmanagers' 返回 [],说明 Prometheus 没连上;日志里有 Failed to send alerts to Alertmanager 并带错误地址。这里正常时再看 amtool check-config 的 route 是否把它丢进没有 receiver 的分支。

根因:Prometheus 只知道一个 Service DNS 名,错一个字符就解析失败,告警停在本地,不重试也不报错到 UI。

修复:kubectl -n platform get svc | grep alertmanager 拿真实名字,改回 CR,等 Operator 重建后复查。

预防:把「activeAlertmanagers 非空」写进 verify-ch13。

13.9 生产对照

本章装的是单副本 Prometheus,保留 6 小时:kind 里够用,生产里第一天就撞墙。

维度学习环境(kind)生产环境为什么迁移动作
Prometheus 副本1 个,本地 emptyDir2 个同配置 + 远端存储,或用 Thanos 查询层单副本一重启就丢采集窗口,告警会在重建期间静默开 replicas: 2 并配 podAntiAffinity
抓取成本与基数3 个 target,指标数在千级按 series 计费,标签是主要成本把 user_id、trace_id 放进标签会让序列数爆炸,内存和查询一起崩抓取前用 metricRelabelings 丢弃高基数标签
告警分级与抑制一条 warning,无抑制P1/P2/P3 分级,上层抑制下层数据库挂了会同时触发几十条「接口慢」,不抑制等于没有告警在 Alertmanager 配 inhibit_rules,按 severity 与 service 匹配
SLO 与错误预算阈值 5%,凭经验按 SLO 反推阈值与燃烧率固定阈值在低流量时误报、高流量时迟钝,预算能把两者统一用 1h/6h 双窗口燃烧率替代裸阈值
保留期6 小时本地 15 天,长期下沉对象存储本地盘是有限的,容量规划要按天算按 retention 与磁盘配额一起定,超了先降采样

13.10 清理

告警与 HPA 可以留着;Prometheus 这套栈占资源多,做完实验建议卸掉。helm uninstall 不会删 CRD。

# env: all
kubectl delete -f deploy/metrics/ --ignore-not-found
# 影响:删掉 ServiceMonitor、HPA、PrometheusRule;shop-api 回到 3 个副本且不再被扩缩
# 回滚:kubectl apply -f deploy/metrics/
helm uninstall kps -n platform
# 影响:Prometheus、Alertmanager、Grafana、Operator 全部删除,platform 里的历史指标丢失
# 回滚:helm upgrade --install kps prometheus-community/kube-prometheus-stack --version 93.2.0 -n platform -f platform/kube-prometheus-stack-values.yaml
kubectl get crd | grep monitoring.coreos.com

最后一条确认 CRD 还在。要彻底清干净就逐个删掉 servicemonitors、prometheusrules 等 CRD;只做实验的话留着更方便,下次装回来不用等重建。

13.11 小结与自测

一句话:指标先有维度,PromQL 才有的算。

一句话:HPA 的分母是 requests,没有它就没有利用率。

一句话:firing 只证明规则成立,收到才算告警。

自测 3 题(点击展开答案)

概念:endpoints[].port 写 8080 和写 http 有什么区别?
答:前者是端口号,后者是端口名。Operator 只按名字匹配,写数字时生成不出 target,也不报错。

排错:HPA 显示 TARGETS 85%/99%,副本一直是 3,正常吗?
答:正常。ceil(3 × 0.85 / 0.99) = 3,期望副本没变。要它扩,把目标降到 70 以下。

决策:错误率规则用 2 分钟还是 15 分钟窗口?
答:2 分钟灵敏但容易抖,适合严重级别;15 分钟平滑但会漏掉尖峰,适合容量决策。生产里常见两个窗口各配一条。

延伸挑战(≤30 分钟)

把错误率规则换成 1 小时 / 5 分钟双窗口的燃烧率,看同样的 5xx 压力下两条规则谁先 firing。提示:慢窗口确认趋势,快窗口负责及时性。

13.12 衔接

回收:第 7 章的 /metrics 被你改成了带标签和直方图的版本,也顺带说明探针与指标为何分开:探针答「能不能接流量」,指标答「接得好不好」。

钩子:你已经能扩缩和告警,但发布还是「一次性替换所有副本」。第 14 章用 HTTPRoute 的 weight 先把 shop-web 新版本放 10% 流量,出错退回 0;本章的错误率规则可以当刹车。

下一章:第 14 章 发布策略:滚动、蓝绿、金丝雀

13.13 参考与验证版本

验证版本:kube-prometheus-stack chart 93.2.0(appVersion v0.95.2,自带 Prometheus v3.13.1 / Alertmanager v0.33.1 / Grafana 13.3.1)· k8s v1.36 · kubectl v1.36 · 最后验证:2026-11-11

变更记录:2026-11-11 首版,对应 chart 93.2.0。

Kubernetes 专题 · S3 第 13 章 指标、扩缩与告警
总目录 · 知识库首页 · SRE 学习路径