2026-11-11 12:57:24 +08:00
<!DOCTYPE html>
< html lang = "zh-CN" data-theme = "light" >
< head >
< meta charset = "utf-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< title > 第 13 章 指标、扩缩与告警 · Kubernetes 专题知识库< / title >
< meta name = "description" content = "给 shop-api 接上 Prometheus: 用 ServiceMonitor 抓指标,用 PromQL 算出错误率与 P95, 让 HPA 在流量高峰把副本从 3 扩到 6, 最后让一条告警规则真的 firing 一次,并看清它为什么会漏。" >
< meta name = "keywords" content = "Kubernetes,Prometheus,ServiceMonitor,PromQL,HPA,Alertmanager,kube-prometheus-stack,告警" >
< link rel = "stylesheet" href = "assets/doc.css" >
< / head >
< body >
< header class = "topbar" >
< div class = "tb-in" >
< a class = "brand" href = "index.html" > < span class = "logo" > K8S< / span > < div > Kubernetes 专题< small > 从第一个 Pod 到生产平台< / small > < / div > < / a >
< div class = "crumbs" >
< a href = "index.html" > 总目录< / a > < span class = "sep" > /< / span > < b > 第 13 章< / b >
< / div >
< div class = "spacer" > < / div >
< button class = "btn" id = "tocToggle" > ☰ 导航< / button >
< button class = "btn" id = "themeBtn" title = "切换到深色主题" > 深色< / button >
< / div >
< / header >
< div class = "layout" id = "layout" >
< aside class = "sidebar" >
< h2 > 章节目录< / h2 >
2026-11-11 22:20:47 +08:00
< nav id = "chapters" > < div class = "toc-stage" > < b > S0< / b > < span class = "h" > 起步:环境与心智< / span > < / div > < a class = "toc-a" href = "00-why.html" > < i class = "cn" > 0< / i > 从一次线上事故理解 K8s< / a > < a class = "toc-a" href = "01-env.html" > < i class = "cn" > 1< / i > 装第一个集群: Windows 11 + WSL2 与 Linux 双轨< / a > < a class = "toc-a" href = "02-kubectl.html" > < i class = "cn" > 2< / i > kubectl 与集群解剖:把黑盒变成可观测对象< / a > < div class = "toc-stage" > < b > S1< / b > < span class = "h" > 跑起来:单服务最小闭环< / span > < / div > < a class = "toc-a" href = "03-pod.html" > < i class = "cn" > 3< / i > Pod: 最小调度单元< / a > < a class = "toc-a" href = "04-deployment.html" > < i class = "cn" > 4< / i > Deployment: 副本与滚动更新< / a > < a class = "toc-a" href = "05-service.html" > < i class = "cn" > 5< / i > Service 与集群 DNS< / a > < a class = "toc-a" href = "06-config.html" > < i class = "cn" > 6< / i > 配置与密钥: ConfigMap 与 Secret< / a > < a class = "toc-a" href = "07-probe.html" > < i class = "cn" > 7< / i > 探针与资源:让它活得像生产< / a > < div class = "toc-stage" > < b > S2< / b > < span class = "h" > 撑得住:状态、入口与多服务< / span > < / div > < a class = "toc-a" href = "08-storage.html" > < i class = "cn" > 8< / i > 存储:从 emptyDir 到 StatefulSet< / a > < a class = "toc-a" href = "09-ingress.html" > < i class = "cn" > 9< / i > 入口与网关: Ingress 与 Gateway API< / a > < a class = "toc-a" href = "10-job.html" > < i class = "cn" > 10< / i > Job 与 CronJob: 迁移与定时任务< / a > < a class = "toc-a" href = "11-multisvc.html" > < i class = "cn" > 11< / i > 多服务与网络策略< / a > < div class = "toc-stage" > < b > S3< / b > < span class = "h" > 看得见:可观测、发布与排障< / span > < / div > < a class = "toc-a" href = "12-logging.html" > < i class = "cn" > 12< / i > 日志:从 kubectl logs 到可检索< / a > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 13< / i > 指标、扩缩与告警< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-13-1" > 13.1 本章在哪< / a > < a class = "toc-a lv3" href = "#sec-13-2" > 13.2 学习目标< / a > < a class = "toc-a lv3" href = "#sec-13-3" > 13.3 场景< / a > < a class = "toc-a lv3" href = "#sec-13-4" > 13.4 心智模型< / a > < a class = "toc-a lv3" href = "#sec-13-5" > 13.5 概念与字段速查< / a > < a class = "toc-a lv3" href = "#sec-13-6" > 13.6 动手< / a > < a class = "toc-a lv3" href = "#sec-13-7" > 13.7 验收< / a > < a class = "toc-a lv3" href = "#sec-13-8" > 13.8 故障实验室< / a > < a class = "toc-a lv3" href = "#sec-13-9" > 13.9 生产对照< / a > < a class = "toc-a lv3" href = "#sec-13-10" > 13.10 清理< / a > < a class = "toc-a lv3" href = "#sec-13-11" > 13.11 小结与自测< / a > < a class = "toc-a lv3" href = "#sec-13-12" > 13.12 衔接< / a > < a class = "toc-a lv3" href = "#sec-13-13" > 13.13 参考与验证版本< / a > < / div > < a class = "toc-a" href = "14-release.html" > < i class = "cn" > 14< / i > 发布策略:滚动、蓝绿、金丝雀< / a > < a class = "toc-a" href = "15-supply.html" > < i class = "cn" > 15< / i > 密钥与镜像供应链< / a > < a class = "toc-a" href = "16-debug.html" > < i class = "cn" > 16< / i > 故障诊断方法论:六类故障,一张诊断树< / a > < div class = "toc-stage" > < b > S4< / b > < span class = "h" > 上生产:集群、调度、安全、交付< / span > < / div > < a class = "toc-a" href = "17-kubeadm.html" > < i class = "cn" > 17< / i > 生产集群搭建: kubeadm HA< / a > < a class = "toc-a" href = "18-schedule.html" > < i class = "cn" > 18< / i > 节点、调度与容量< / a > < a class = "toc-a" href = "19-rbac.html" > < i class = "cn" > 19< / i > 安全基线: RBAC 与准入< / a > < a class = "toc-a" href = "20-gitops.html" > < i class = "cn" > 20< / i > GitOps: Helm/Kustomize + Argo CD< / a > < a class = "toc-a" href = "21-ci.html" > < i class = "cn" > 21< / i > CI/CD 流水线< / a > < a class = "toc-a" href = "22-backup.html" > < i class = "cn" > 22< / i > 备份、恢复与升级< / a > < div class = "toc-stage" > < b > S5< / b > < span class = "h" > 守得住:值班、成本与评审< / span > < / div > < a class = "toc-a" href = "23-oncall.html" > < i class = "cn" > 23< / i > 值班与事故响应< / a > < a class = "toc-a" href = "24-cost.html" > < i class = "cn" > 24< / i > 成本与容量< / a > < a class = "toc-a" href = "25-prr.html" > < i class = "cn" > 25< / i > 生产就绪评审与下一步< / a > < / nav >
2026-11-11 12:57:24 +08:00
< div class = "side-foot" >
< a class = "btn" href = "index.html" > ← 总目录< / a >
< / div >
< / aside >
< div class = "mask" id = "mask" > < / div >
< main class = "main-col" >
< article >
< p class = "chapnav" >
< a href = "index.html" > Kubernetes 专题< / a >
< span > ·< / span >
< span > S3 看得见:可观测、发布与排障< / span >
< span > ·< / span >
< span > 第 < b class = "pos" > 13< / b > / 26 章< / span >
< / p >
< h2 id = "ch13" > < span class = "n" > 13< / span > 指标、扩缩与告警< / h2 >
< div class = "lead" >
2026-11-11 21:57:56 +08:00
< b > 30 秒速览:< / b > < code > kubectl top< / code > 只答「此刻多少」。本章把它变成「过去一小时」和一条会自己响的告警:装 kube-prometheus-stack、抓指标、写 PromQL 算错误率与 P95、让 HPA 从 3 扩到 6, 最后让一条规则真的 firing。
2026-11-11 12:57:24 +08:00
< / div >
< h3 id = "sec-13-1" > 13.1 本章在哪< / h3 >
< p > 第 7 章你给 shop-api 加了 < code > /healthz< / code > 和 < code > /metrics< / code > ,并装了 metrics-server, 于是 < code > kubectl top pod< / code > 能报出每个 Pod 的 CPU。但那份能力只够回答「现在多少」: 高峰过后, 它什么都不记得, 也不会叫醒任何人。< / p >
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 位置< / th > < th > 内容< / th > < / tr >
< / thead >
< tbody >
< tr > < td > 主线之前< / td > < td > 第 7 章装好的 metrics-server 与 shop-api 的 < code > /metrics< / code > ;第 12 章的日志管道< / td > < / tr >
< tr > < td > 主线之后< / td > < td > < code > shop< / code > 里的 ServiceMonitor、HPA、PrometheusRule; < code > platform< / code > 里的一整套 Prometheus 与 Alertmanager< / td > < / tr >
< tr > < td > 本章产物< / td > < td > < code > platform/kube-prometheus-stack-values.yaml< / code > 、< code > deploy/metrics/< / code > 下三个清单、改过的 < code > apps/shop-api/main.go< / code > < / td > < / tr >
< tr > < td > 适用环境< / td > < td > kind 单集群, CPU 建议给到 6 核以上; Prometheus 与 Grafana 都是真实工作负载< / td > < / tr >
< / tbody >
< / table >
< / div >
< h3 id = "sec-13-2" > 13.2 学习目标< / h3 >
< div class = "box note" >
< span class = "bt" > 学完你能< / span >
< ul >
< li > 解释 ServiceMonitor、Service、Endpoints 如何匹配出一个抓取目标。< br > < b > 判定标准< / b > :能说出「端口名写错」会让 target 消失在哪一步。< / li >
< li > 用 PromQL 写出错误率与 P95, 并说明窗口的取舍。< br > < b > 判定标准< / b > :换个窗口,你能说出曲线会变钝还是变尖。< / li >
< li > 让 HPA 稳定扩容,并说清它为什么不扩容。< br > < b > 判定标准< / b > :看到 < code > TARGETS 85%/99%< / code > 能算出期望副本数。< / li >
< li > 让一条告警从表达式走到 Alertmanager, 并定位断点。< br > < b > 判定标准< / b > :会查 < code > /api/v1/alertmanagers< / code > 与 < code > /api/v1/rules< / code > 。< / li >
< / ul >
< / div >
< h3 id = "sec-13-3" > 13.3 场景< / h3 >
< p > 周五晚上八点,一场投放把 < code > shop.example.com< / code > 的流量推到平时四倍。shop-api 三个副本 CPU 全部贴着 limit 跑,请求排队,超时后网关返回 502, 应用自己吐 500。没有人收到通知: 告警群最后一条消息是三个月前的。< / p >
< p > 周六上午十点,有人翻 Grafana 才发现:昨天 20:00 到 21:30, 5xx 比例最高到过 12%,持续近二十分钟。复盘时最刺人的一句是「不是监控没报,是我们根本没有监控」。< / p >
< p > 你现有的工具是 < code > kubectl top< / code > :采样点,不留历史,没阈值,没有通知渠道。本章补上四件事:指标被采集、被计算、被扩缩用、异常被人知道。任何一环断掉,后面全是摆设。< / p >
< h3 id = "sec-13-4" > 13.4 心智模型< / h3 >
< p > 把本章想成两条并行的链路,见图 1。上面是「指标链」: 应用暴露 < code > /metrics< / code > , ServiceMonitor 描述怎么抓, Prometheus 拉取存储, PrometheusRule 周期求值,结果推给 Alertmanager 路由。下面是「扩缩链」: metrics-server 定期问 kubelet 要用量, HPA 读它算期望副本,最后改 Deployment 的 < code > replicas< / code > 。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 720 340" role = "img" aria-label = "指标链与扩缩链" >
< defs >
< marker id = "a13" markerWidth = "9" markerHeight = "9" refX = "8" refY = "4.5" orient = "auto" > < path d = "M0,0 L9,4.5 L0,9 z" style = "fill:var(--muted)" > < / path > < / marker >
< / defs >
< text x = "20" y = "30" style = "fill:var(--muted);font-size:12px" > 指标链:一次抓取到一次通知< / text >
< rect x = "20" y = "48" width = "120" height = "64" rx = "6" style = "fill:var(--brand-soft);stroke:var(--line)" > < / rect >
< text x = "80" y = "74" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > shop-api< / text >
< text x = "80" y = "94" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > :8080/metrics< / text >
< rect x = "160" y = "48" width = "120" height = "64" rx = "6" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "220" y = "74" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > ServiceMonitor< / text >
< text x = "220" y = "94" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 怎么抓< / text >
< rect x = "300" y = "48" width = "120" height = "64" rx = "6" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "360" y = "74" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > Prometheus< / text >
< text x = "360" y = "94" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 拉取并存储< / text >
< rect x = "440" y = "48" width = "120" height = "64" rx = "6" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "500" y = "74" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > PrometheusRule< / text >
< text x = "500" y = "94" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 周期性求值< / text >
< rect x = "580" y = "48" width = "120" height = "64" rx = "6" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "640" y = "74" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > Alertmanager< / text >
< text x = "640" y = "94" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 路由与分组< / text >
< path d = "M140,80 L156,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13)" > < / path >
< path d = "M280,80 L296,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13)" > < / path >
< path d = "M420,80 L436,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13)" > < / path >
< path d = "M560,80 L576,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13)" > < / path >
< text x = "20" y = "196" style = "fill:var(--muted);font-size:12px" > 扩缩链:一次采样到一个新副本< / text >
< rect x = "60" y = "214" width = "140" height = "64" rx = "6" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "130" y = "240" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > metrics-server< / text >
< text x = "130" y = "260" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 15s 聚合一次< / text >
< rect x = "280" y = "214" width = "140" height = "64" rx = "6" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "350" y = "240" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > HPA< / text >
< text x = "350" y = "260" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 算期望副本< / text >
< rect x = "500" y = "214" width = "140" height = "64" rx = "6" style = "fill:var(--brand-soft);stroke:var(--line)" > < / rect >
< text x = "570" y = "240" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > Deployment< / text >
< text x = "570" y = "260" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > replicas 3 → 6< / text >
< path d = "M200,246 L276,246" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13)" > < / path >
< path d = "M420,246 L496,246" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13)" > < / path >
< path d = "M570,214 L570,118" style = "stroke:var(--muted);fill:none;stroke-dasharray:4 4" marker-end = "url(#a13)" > < / path >
< text x = "582" y = "170" style = "fill:var(--muted);font-size:11px" > 同一个 Deployment< / text >
< / svg >
< div class = "figcap" > < b > 图 1 ·< / b > 两条链路只在 shop-api 这个对象上相交,其余环节互不知情。< / div >
< / figure >
< p > 两条链的交点只有 shop-api: 上面一条看它的输出, 下面一条改它的副本数。所以先把指标做成能算错误率的样子, 再谈扩缩和告警——维度不对, 后面的 PromQL 与规则全是空转。< / p >
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 常见误解< / th > < th > 实际是什么< / th > < / tr >
< / thead >
< tbody >
< tr > < td > 有了 metrics-server 就有监控< / td > < td > 它只保留最近十几分钟的资源用量,没有历史、没有查询语言、没有告警,副本一重建数据就断< / td > < / tr >
< tr > < td > HPA 看的是节点的 CPU< / td > < td > 看的是 Pod 的 < code > requests.cpu< / code > 占比,没有 requests 的 Pod 在它眼里是 < code > < unknown> < / code > < / td > < / tr >
< tr > < td > 告警是 Prometheus 发出去的< / td > < td > Prometheus 只负责在阈值上停留够久后置为 firing, 发不发、发给谁由 Alertmanager 的 route 决定< / td > < / tr >
< / tbody >
< / table >
< / div >
< h3 id = "sec-13-5" > 13.5 概念与字段速查< / h3 >
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 对象 / 字段< / th > < th > 作用< / th > < th > 默认值< / th > < th > 生产建议< / th > < / tr >
< / thead >
< tbody >
< tr > < td > < code > ServiceMonitor< / code > < code > spec.endpoints[].port< / code > < / td > < td > 指定抓哪个端口,值必须是 Service 里的端口名< / td > < td > 无,必填< / td > < td > 给端口起有意义的名字,如 < code > http-metrics< / code > < / td > < / tr >
< tr > < td > < code > ServiceMonitor< / code > < code > spec.endpoints[].interval< / code > < / td > < td > 抓取周期< / td > < td > 跟随 Prometheus 的 < code > scrapeInterval< / code > , 30s< / td > < td > 核心服务 15s, 边缘服务 60s< / td > < / tr >
< tr > < td > < code > Prometheus< / code > < code > serviceMonitorSelectorNilUsesHelmValues< / code > < / td > < td > 为真时只选带 release 标签的 ServiceMonitor< / td > < td > true< / td > < td > 置 false, 或给自建对象补 < code > release< / code > 标签< / td > < / tr >
< tr > < td > < code > Prometheus< / code > < code > ruleSelectorNilUsesHelmValues< / code > < / td > < td > 同上,作用于 PrometheusRule< / td > < td > true< / td > < td > 与上一行保持一致< / td > < / tr >
< tr > < td > < code > Prometheus< / code > < code > retention< / code > < / td > < td > 本地 TSDB 保留时长< / td > < td > 10d< / td > < td > 按磁盘与查询需求定,长留存下沉到远端存储< / td > < / tr >
< tr > < td > < code > PrometheusRule< / code > < code > spec.groups[].rules[].for< / code > < / td > < td > 表达式连续为真多久才 firing< / td > < td > 0s< / td > < td > 至少覆盖两个求值周期,避免抖动< / td > < / tr >
< tr > < td > < code > HorizontalPodAutoscaler< / code > < code > averageUtilization< / code > < / td > < td > 目标 CPU 利用率,按 requests 计算< / td > < td > 无,资源型指标必填< / td > < td > 60– 80, 留出突发余量< / td > < / tr >
< tr > < td > < code > metrics-server< / code > < code > --metric-resolution< / code > < / td > < td > 采集间隔,决定 HPA 的反应速度< / td > < td > 15s< / td > < td > 保持默认,改小只会增加 apiserver 压力< / td > < / tr >
< / tbody >
< / table >
< / div >
< details >
< summary > 可跳过 · HPA 的期望副本数是怎么算出来的< / summary >
< p > 资源型指标的公式是 < code > 期望副本 = ceil(当前副本 × 当前利用率 / 目标利用率)< / code > ,结果夹在 min 与 max 之间。利用率的分母是就绪 Pod 的 requests 之和,不是 limit——把 limit 调大不会更早扩容。< / p >
< / details >
< p class = "take" > < b > 一句话:< / b > ServiceMonitor 决定抓不抓得到, PromQL 决定算不算得对, HPA 只信 requests。< / p >
< h3 id = "sec-13-6" > 13.6 动手< / h3 >
< p > 先交代本章唯一要改的应用代码。第 7 章给 shop-api 的 < code > /metrics< / code > 只有一个计数器 < code > shop_api_requests_total< / code > ,没有 < code > status< / code > 标签:它算得出 QPS, 算不出错误率。为了让 PromQL 与生产里的通用写法对齐,这里扩一次指标:< / p >
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 关注点< / th > < th > 改动前(第 7 章)< / th > < th > 改动后(本章)< / th > < th > 为什么< / th > < / tr >
< / thead >
< tbody >
< tr > < td > 指标名< / td > < td > < code > shop_api_requests_total< / code > < / td > < td > < code > http_requests_total< / code > < / td > < td > 去掉应用前缀,换成社区通用的命名,表达式可以原样搬到别的服务< / td > < / tr >
< tr > < td > 标签< / td > < td > 无< / td > < td > < code > status="200"< / code > < code > status="500"< / code > < / td > < td > 错误率需要分子,靠标签才拆得开< / td > < / tr >
< tr > < td > 耗时< / td > < td > 无< / td > < td > < code > http_request_duration_seconds_bucket< / code > < / td > < td > P95 只能从直方图的桶里算,平均值给不出尾部< / td > < / tr >
< tr > < td > 抓取副作用< / td > < td > 抓一次 < code > /metrics< / code > 也计数< / td > < td > 抓取与业务分开统计< / td > < td > 否则抓取频率会污染错误率的分母< / td > < / tr >
< tr > < td > 演练入口< / td > < td > 无< / td > < td > < code > /fail< / code > 返回 500< / td > < td > 造 5xx 不需要真的弄坏数据库< / td > < / tr >
< / tbody >
< / table >
< / div >
< h4 > Step 1 · 校验第 12 章留下的现场< / h4 >
2026-11-11 22:20:47 +08:00
< p > < span class = "tag" > 意图< / span > 确认三个副本都在、metrics-server 仍健康。< / p >
2026-11-11 12:57:24 +08:00
< pre data-lang = "bash" data-name = "校验 ch12 与前置组件" > # env: all
cd ~/work/aurora-shop
make verify-ch12
kubectl -n shop get deploy shop-api
kubectl -n kube-system get deploy metrics-server< / pre >
< p > < b > 预期输出< / b > : < code > make verify-ch12< / code > 打印 ok 并退出 0; < code > shop-api< / code > 是 < code > 3/3< / code > , < code > metrics-server< / code > 是 < code > 1/1< / code > ; < code > kubectl top pod -n shop< / code > 返回数字。< / p >
< p > < b > 不一致怎么办< / b > : < code > kubectl top< / code > 报错时先看 < code > kubectl -n kube-system get apiservice v1beta1.metrics.k8s.io< / code > 的 < code > AVAILABLE< / code > 列。它是 < code > False< / code > 时本章的负向现象会提前出现,先修它。< / p >
< h4 > Step 2 · 把 /metrics 改成能算错误率的样子< / h4 >
< p > < span class = "tag" > 意图< / span > 给计数器加 < code > status< / code > 标签,补一个耗时直方图,再开一个只用于演练的 < code > /fail< / code > 端点。< / p >
< pre data-lang = "go" data-name = "apps/shop-api/main.go( 改动后) " > // 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))< / pre >
< p > < code > withMetrics< / code > 用 < code > WriteHeader< / code > 截住状态码,所以 500 是应用自己产生的;< code > recorder< / code > 默认记 200。< / p >
< pre data-lang = "bash" data-name = "重建镜像并滚动" > # 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< / pre >
< p > < b > 预期输出< / b > : < code > rollout status< / code > 打印 < code > deployment "shop-api" successfully rolled out< / code > ; < code > curl< / code > 的前几行是新的指标名。< / p >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
# 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< / pre >
< p > < b > 不一致怎么办< / b > :还是旧指标名说明 Pod 没换镜像,看 < code > Image ID< / code > 。< / p >
< div class = "grid2" >
< div class = "box" >
< h4 > Windows 11 + WSL2< / h4 >
< p > < code > make image< / code > 调用的 < code > docker< / code > 可能来自 Docker Desktop。跑 < code > docker context show< / code > ,看到 < code > desktop-linux< / code > 说明镜像建在虚拟机里,< code > kind load< / code > 仍取得到。< / p >
< / div >
< div class = "box" >
< h4 > Linux (Ubuntu 24.04)< / h4 >
< p > < code > docker< / code > 就是本机的 dockerd, < code > systemctl is-active docker< / code > 返回 < code > active< / code > 即可。< code > kind load< / code > 直接从本地镜像库读,没有额外的层要同步。< / p >
< / div >
< / div >
< p > < b > 差异结论< / b > : 命令完全一样, 差别只在镜像由谁构建。WSL 报 < code > Cannot connect to the Docker daemon< / code > 时先确认 Docker Desktop 已启动,别去改 Makefile。< / p >
< div class = "box warn" >
< span class = "bt" > 易错点 · 指标改了,抓到的还是旧数字< / span >
< p > < b > 现象< / b > : < code > curl /metrics< / code > 已经有 < code > http_requests_total< / code > ,但 Prometheus 里查不到这个指标名。< / p >
< p > < b > 原因< / b > : < code > make load< / code > 只把镜像推进节点, Pod 仍跑着旧镜像;或者 rollout 完成但 Prometheus 还没到下一个抓取周期。< / p >
< p > < b > 怎么验证< / b > : < code > kubectl -n shop get pod -o jsonpath='{.items[0].status.containerStatuses[0].imageID}'< / code > 与 < code > docker images --digests< / code > 对一下摘要,再等一个 < code > interval< / code > 。< / p >
< / div >
< h4 > Step 3 · 把 kube-prometheus-stack 装进 platform< / h4 >
< p > < span class = "tag" > 意图< / span > 装上 Prometheus、Alertmanager、Grafana 与 Operator 四件套,并把选择器改成「认所有 ServiceMonitor」。< / p >
< pre data-lang = "bash" data-name = "安装 kube-prometheus-stack 93.2.0" > # 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< / pre >
< p > < b > 预期输出< / b > : < code > STATUS: deployed< / code > ,随后 < code > kubectl -n platform get pod< / code > 里 Operator、Prometheus、Alertmanager、Grafana 四个 Pod 全是 < code > Running< / code > ; < code > get prometheus< / code > 的 < code > AVAILABLE< / code > 为 < code > 1/1< / code > 。< / p >
< p > < b > 不一致怎么办< / b > : < code > --wait< / code > 超时多半是镜像还在拉,看 < code > ImagePullBackOff< / code > 。< / p >
< p > 两个 < code > *SelectorNilUsesHelmValues: false< / code > 是本章的关键开关。它们为 < code > true< / code > 时 Operator 只收带 < code > release: kps< / code > 标签的对象,你新建的 ServiceMonitor 会被静默忽略——不报错,也不抓。< / p >
< h4 > Step 4 · 用一个 ServiceMonitor 抓到 shop-api< / h4 >
< p > < span class = "tag" > 意图< / span > 让 Prometheus 认领 shop-api 的 < code > /metrics< / code > ,并确认三个副本各产生一个 target。< / p >
< pre data-lang = "yaml" data-name = "deploy/metrics/shop-api-servicemonitor.yaml" > # 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< / pre >
< p > 图 2 的三处匹配里,< code > endpoints[].port< / code > 只认端口名;写数字时 Operator 匹配不到,直接在生成的配置里跳过这条,不报错。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 720 300" role = "img" aria-label = "ServiceMonitor 的三处匹配" >
< defs >
< marker id = "a13b" markerWidth = "9" markerHeight = "9" refX = "8" refY = "4.5" orient = "auto" > < path d = "M0,0 L9,4.5 L0,9 z" style = "fill:var(--muted)" > < / path > < / marker >
< / defs >
< rect x = "20" y = "26" width = "230" height = "60" rx = "6" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "34" y = "50" style = "fill:var(--ink);font-size:12px" > ServiceMonitor< / text >
< text x = "34" y = "70" style = "fill:var(--muted);font-size:11px" > spec.selector.matchLabels< / text >
< rect x = "20" y = "112" width = "230" height = "60" rx = "6" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "34" y = "136" style = "fill:var(--ink);font-size:12px" > Service< / text >
< text x = "34" y = "156" style = "fill:var(--muted);font-size:11px" > metadata.labels + spec.ports[].name< / text >
< rect x = "20" y = "198" width = "230" height = "60" rx = "6" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "34" y = "222" style = "fill:var(--ink);font-size:12px" > Endpoints< / text >
< text x = "34" y = "242" style = "fill:var(--muted);font-size:11px" > 真实 Pod IP 与端口号< / text >
< rect x = "330" y = "90" width = "170" height = "104" rx = "6" style = "fill:var(--brand-soft);stroke:var(--line)" > < / rect >
< text x = "415" y = "126" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > Prometheus 生成< / text >
< text x = "415" y = "146" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > 一个 target< / text >
< text x = "415" y = "168" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 标签 job=shop-api< / text >
< rect x = "560" y = "90" width = "140" height = "104" rx = "6" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "630" y = "126" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > up == 1< / text >
< text x = "630" y = "148" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 才算抓成功< / text >
< text x = "630" y = "168" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 每个副本一条< / text >
< path d = "M250,56 L326,110" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13b)" > < / path >
< path d = "M250,142 L326,142" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13b)" > < / path >
< path d = "M250,228 L326,176" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13b)" > < / path >
< path d = "M500,142 L556,142" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13b)" > < / path >
< / svg >
< div class = "figcap" > < b > 图 2 ·< / b > 三处匹配任何一处不成立, target 就不会出现;出现但 < code > up< / code > 为 0 则是网络或路径问题。< / div >
< / figure >
< pre data-lang = "bash" data-name = "应用并核对 target" > # 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'< / pre >
< p > < b > 预期输出< / b > :端口名是 < code > http< / code > ,三行 < code > up< / code > ,各指向一个 Pod IP 的 8080。< / p >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
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< / pre >
< p > < b > 不一致怎么办< / b > :按故障 1 的两步查配置与端口名。< / p >
< h4 > Step 5 · 四条 PromQL, 把「此刻」变成「趋势」< / h4 >
< p > < span class = "tag" > 意图< / span > 用四个查询回答四个问题:抓到了吗、量多大、错多少、慢不慢。< / p >
< pre data-lang = "bash" data-name = "在 Prometheus 上跑四条查询" > # 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])))'< / pre >
< p > < b > 预期输出< / b > :第一行健康副本数,第二行 QPS, 第三行错误率, 第四行 P95 秒数。< / p >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
all 3
all 2.4133
all 0.0000
all 0.0412< / pre >
< p > < b > 不一致怎么办< / b > :结果为空说明样本不够,等一个抓取周期。< / p >
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 想回答的问题< / th > < th > PromQL< / th > < th > 为什么这么写< / th > < / tr >
< / thead >
< tbody >
< tr > < td > 几个副本在被抓< / td > < td > < code > count(up{job="shop-api"} == 1)< / code > < / td > < td > < code > up< / code > 是抓取元数据,不做过滤会把历史序列也算进去< / td > < / tr >
< tr > < td > 每秒多少请求< / td > < td > < code > sum(rate(http_requests_total[2m]))< / code > < / td > < td > 计数器必须先 < code > rate< / code > ,直接对累计值求和无意义< / td > < / tr >
< tr > < td > 错误率< / td > < td > < code > sum(rate(http_requests_total{status=~"5.."}[2m])) / sum(rate(http_requests_total[2m]))< / code > < / td > < td > 分子分母同窗口,且先分别 < code > sum< / code > 再相除,避免分副本相除后取平均< / td > < / tr >
< tr > < td > P95 延迟< / td > < td > < code > histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))< / code > < / td > < td > 桶必须先按 < code > le< / code > 聚合,否则算的是某个副本的分位数< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 窗口取 2 分钟: 15 秒间隔下有 8 个样本, 够平滑也不糊掉尖峰。P95 用 5 分钟,因为分位数对样本量更敏感。< / p >
< h4 > Step 6 · 让 HPA 从 3 扩到 6< / h4 >
< p > < span class = "tag" > 意图< / span > 用 CPU 利用率做扩缩信号:先看到 < code > TARGETS< / code > 有百分数,再用真实压力推到 6 个副本。< / p >
< pre data-lang = "yaml" data-name = "deploy/metrics/shop-api-hpa.yaml" > # 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< / pre >
< pre data-lang = "bash" data-name = "应用 HPA 并压测" > # 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< / pre >
< p > < b > 预期输出< / b > :刚创建时 < code > REPLICAS< / code > 是 3、< code > TARGETS< / code > 是一个小百分数;压测三分钟后副本变成 6, 利用率回落到 70% 上下。< / p >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
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< / pre >
< p > < b > 不一致怎么办< / b > : < code > TARGETS< / code > 是 < code > < unknown> < / code > 就回到故障 2。< / p >
< p > 六个循环是每副本两个;< code > kubectl exec deploy/…< / code > 只选一个 Pod。< / p >
< p > < span class = "tag" > 意图< / span > 反过来验证一次:把目标调高,看它为什么不动。< / p >
< pre data-lang = "bash" data-name = "负向验证:目标 99%" > # 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< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
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< / pre >
< p > 一次扩一次缩。目标 99% 不是更容易触发, 而是更晚触发: 85% 利用率下 < code > ceil(3 × 85 / 99) = 3< / code > ,期望副本没变,它只在 Events 里写一句 < code > All metrics below target< / code > 。< / p >
< div class = "box warn" >
< span class = "bt" > 易错点 · 压测还没停就改目标< / span >
< p > < b > 现象< / b > :改成 99% 之后副本反而从 3 涨到 6, 和预期相反。< / p >
< p > < b > 原因< / b > :利用率仍高于 99%, < code > ceil(3 × 2.14 / 0.99) = 7< / code > ,被 max 夹到 6。目标只是分母, 压力还在就还会扩。< / p >
< p > < b > 怎么验证< / b > :看 < code > TARGETS< / code > 左边那个数是否已落到 99 以下。< / p >
< / div >
< h4 > Step 7 · 让一条告警真的 firing 一次< / h4 >
< p > < span class = "tag" > 意图< / span > 写一条错误率规则,用 < code > /fail< / code > 稳定制造 5xx, 看它从 inactive 走到 pending 再到 firing, 并在 Alertmanager 里查到同一条。< / p >
< pre data-lang = "yaml" data-name = "deploy/metrics/shop-api-rules.yaml" > # 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 }}。"< / pre >
< p > 状态机见图 3。每次求值为真 < code > pending< / code > 计时器走一格,连续为真满 < code > for< / code > 才进 < code > firing< / code > ;中间有一次为假就回到 < code > inactive< / code > 。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 720 260" role = "img" aria-label = "告警状态机" >
< defs >
< marker id = "a13c" markerWidth = "9" markerHeight = "9" refX = "8" refY = "4.5" orient = "auto" > < path d = "M0,0 L9,4.5 L0,9 z" style = "fill:var(--muted)" > < / path > < / marker >
< / defs >
< rect x = "20" y = "80" width = "140" height = "56" rx = "6" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "90" y = "112" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > inactive< / text >
< rect x = "190" y = "80" width = "140" height = "56" rx = "6" style = "fill:var(--warn-bg);stroke:var(--line)" > < / rect >
< text x = "260" y = "112" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > pending< / text >
< rect x = "360" y = "80" width = "140" height = "56" rx = "6" style = "fill:var(--danger);stroke:var(--line)" > < / rect >
< text x = "430" y = "112" text-anchor = "middle" style = "fill:var(--card);font-size:12px" > firing< / text >
< rect x = "530" y = "80" width = "140" height = "56" rx = "6" style = "fill:var(--ok-bg);stroke:var(--line)" > < / rect >
< text x = "600" y = "112" text-anchor = "middle" style = "fill:var(--ink);font-size:12px" > resolved< / text >
< path d = "M160,108 L186,108" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13c)" > < / path >
< path d = "M330,108 L356,108" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13c)" > < / path >
< path d = "M500,108 L526,108" style = "stroke:var(--muted);fill:none" marker-end = "url(#a13c)" > < / path >
< text x = "173" y = "66" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 表达式为真< / text >
< text x = "343" y = "66" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 持续 for< / text >
< text x = "513" y = "66" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 表达式为假< / text >
< path d = "M430,136 L430,196 L90,196 L90,140" style = "stroke:var(--muted);fill:none;stroke-dasharray:4 4" marker-end = "url(#a13c)" > < / path >
< text x = "260" y = "218" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > pending 中途断掉也走这条路< / text >
< / svg >
< div class = "figcap" > < b > 图 3 ·< / b > Alertmanager 只看到 firing 与 resolved 两端,中间过程在 Prometheus 里。< / div >
< / figure >
< pre data-lang = "bash" data-name = "制造 5xx 并核对告警" > # 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'< / pre >
< p > < b > 预期输出< / b > : < code > for: 2m< / code > 走完后状态是 < code > firing< / code > ,值在 0.9 以上;第二行是 Alertmanager 的地址。刚 apply 时先显示 < code > pending< / code > 。< / p >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
firing 0.9773
http://kps-kube-prometheus-stack-alertmanager.platform.svc:9093/api/v2/alerts< / pre >
< p > < b > 不一致怎么办< / b > :一直 < code > pending< / code > 说明期间有一次求值为假。< / p >
< div class = "box note" >
< span class = "bt" > 关于 /fail< / span >
< p > 这个端点只负责稳定产生 500。真实环境更常见的做法是把 < code > DATABASE_URL< / code > 指向不存在的库,让 < code > /< / code > 自己返回 500——那验证真实失败路径, < code > /fail< / code > 验证告警链路,不要留在生产镜像里。< / p >
< / div >
< div class = "box warn" >
< span class = "bt" > 易错点 · 告警一直在 pending< / span >
< p > < b > 现象< / b > :错误率明明已经 90% 以上,规则状态却停在 < code > pending< / code > ,或者刚 firing 又掉回 < code > inactive< / code > 。< / p >
< p > < b > 原因< / b > : < code > for: 2m< / code > 要求连续为真; 压测循环被打断、Pod 重建、或窗口内样本不足都会让某次求值为假。< / p >
< p > < b > 怎么验证< / b > :在 Prometheus 页面上直接把 < code > expr< / code > 贴进查询框,看曲线在这两分钟里有没有掉到 0.05 以下。< / p >
< / div >
< h4 > Step 8 · 提交产物< / h4 >
< p > < span class = "tag" > 意图< / span > 把本章新增的四个文件和改动过的 < code > main.go< / code > 一起提交,让第 14 章从干净的现场开始。< / p >
< pre data-lang = "bash" data-name = "提交本章产物" > # 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< / pre >
< p > < b > 预期输出< / b > : < code > git status --short< / code > 无输出(工作区干净),提交信息一行。< / p >
< p > < b > 不一致怎么办< / b > :还有残留文件就先看清路径,别把临时改动带进去。< / p >
< h3 id = "sec-13-7" > 13.7 验收< / h3 >
< p > 按顺序做完五条才算通过:前三条验配置,后两条验行为。只做完前三条的人,往往到第 14 章才发现告警从没响过。< / p >
< ol class = "steps" >
< li > < code > servicemonitor shop-api< / code > 存在, Prometheus 的 < code > availableReplicas< / code > 为 1, < code > /api/v1/targets< / code > 里三个 < code > job="shop-api"< / code > 都是 < code > up< / code > 。< / li >
< li > HPA 的 < code > TARGETS< / code > 是 < code > N%/70%< / code > ,不是 < code > < unknown> /70%< / code > 。< / li >
< li > 压测三分钟后 < code > REPLICAS< / code > 从 3 到 6, 停止压测后回落。< / li >
< li > < code > kubectl -n shop get prometheusrule shop-api-rules< / code > 存在,< code > /api/v1/rules< / code > 里能看到 < code > ShopApiHighErrorRate< / code > 。< / li >
< li > 打 < code > /fail< / code > 两分钟后规则为 < code > firing< / code > , < code > activeAlertmanagers< / code > 非空。< / li >
< / ol >
< p > 把这五条固化成 < code > make verify-ch13< / code > :查对象是否齐全,抓两个 API 校验 target 与规则,确认 < code > TARGETS< / code > 带百分号。反向验证:把 < code > port< / code > 改错,脚本必须在第 1 条失败。< / p >
< p class = "take" > < b > 一句话:< / b > 验收要验「响过」,不是验「配了」。< / p >
< h3 id = "sec-13-8" > 13.8 故障实验室< / h3 >
< div class = "box danger" >
< span class = "bt" > 故障 1 · ServiceMonitor 建了, Target 却不出现< / span >
< p > < b > 注入< / b > :把 < code > spec.endpoints[0].port< / code > 从 < code > http< / code > patch 成不存在的 < code > metrics< / code > 。< / p >
< p > < b > 症状< / b > : < code > kubectl get servicemonitor< / code > 正常,< code > describe< / code > 没有事件; target 列表里 < code > job="shop-api"< / code > 直接消失,不是 < code > down< / code > ,是没有。< / p >
< p > < b > 诊断< / b > :看 Operator 有没有把它写进配置。< code > 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< / code > 。输出 0 说明问题在选择器或标签,输出 1 说明在端口名。< / p >
< p > < b > 根因< / b > :三处匹配(图 2) 任一断裂。最常见的是端口名写错; 其次是 < code > serviceMonitorSelectorNilUsesHelmValues< / code > 仍为 true 而对象没带 < code > release< / code > 标签。< / p >
< p > < b > 修复< / b > :把 < code > port< / code > 改回 < code > http< / code > ,一分钟后 target 回来。< / p >
< p > < b > 预防< / b > : ServiceMonitor 与 Service 同目录评审,端口名不手写。< / p >
< / div >
< div class = "box danger" >
< span class = "bt" > 故障 2 · HPA 一直是 TARGETS < unknown> /70%< / span >
< p > < b > 注入< / b > :删掉 Deployment 里的 < code > resources.requests< / code > 整块。< / p >
< p > < b > 症状< / b > : < code > TARGETS< / code > 变成 < code > < unknown> /70%< / code > ,副本数停在 < code > MINPODS< / code > ,压力再大也不动。< / p >
< p > < b > 诊断< / b > : < code > kubectl -n shop describe hpa shop-api< / code > 的 Events 里有一行 < code > failed to get cpu utilization: missing request for cpu< / code > 。若换成 < code > unable to fetch metrics from resource metrics API< / code > ,那是 metrics-server 的问题,方向不同。< / p >
< p > < b > 根因< / b > :利用率的分母是 requests 之和;没有 requests 就没有分母。HPA 拿不到指标时不会乐观扩容,只会停手。< / p >
< p > < b > 修复< / b > :把 requests 加回去并确认滚动完成。< / p >
< p > < b > 预防< / b > :准入层强制 requests, 或用 LimitRange 给默认值。< / p >
< / div >
< div class = "box danger" >
< span class = "bt" > 故障 3 · 规则 firing 了, Alertmanager 却没收到< / span >
< p > < b > 注入< / b > :把 Prometheus CR 的 < code > alerting.alertmanagers[0].name< / code > 改成 < code > alertmanager< / code > ,而真实服务名带 < code > kps-kube-prometheus-stack-< / code > 前缀。< / p >
< p > < b > 症状< / b > : < code > /api/v1/rules< / code > 里是 < code > firing< / code > , Alertmanager 的 < code > /api/v2/alerts< / code > 却是空数组,一条通知都没发。< / p >
< p > < b > 诊断< / b > : < code > curl -s localhost:9090/api/v1/alertmanagers | jq '.data.activeAlertmanagers'< / code > 返回 < code > []< / code > ,说明 Prometheus 没连上;日志里有 < code > Failed to send alerts to Alertmanager< / code > 并带错误地址。这里正常时再看 < code > amtool check-config< / code > 的 route 是否把它丢进没有 receiver 的分支。< / p >
< p > < b > 根因< / b > : Prometheus 只知道一个 Service DNS 名,错一个字符就解析失败,告警停在本地,不重试也不报错到 UI。< / p >
< p > < b > 修复< / b > : < code > kubectl -n platform get svc | grep alertmanager< / code > 拿真实名字,改回 CR, 等 Operator 重建后复查。< / p >
< p > < b > 预防< / b > : 把「activeAlertmanagers 非空」写进 < code > verify-ch13< / code > 。< / p >
< / div >
< h3 id = "sec-13-9" > 13.9 生产对照< / h3 >
< p > 本章装的是单副本 Prometheus, 保留 6 小时: kind 里够用,生产里第一天就撞墙。< / p >
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 维度< / th > < th > 学习环境( kind) < / th > < th > 生产环境< / th > < th > 为什么< / th > < th > 迁移动作< / th > < / tr >
< / thead >
< tbody >
< tr > < td > Prometheus 副本< / td > < td > 1 个,本地 emptyDir< / td > < td > 2 个同配置 + 远端存储,或用 Thanos 查询层< / td > < td > 单副本一重启就丢采集窗口,告警会在重建期间静默< / td > < td > 开 < code > replicas: 2< / code > 并配 < code > podAntiAffinity< / code > < / td > < / tr >
< tr > < td > 抓取成本与基数< / td > < td > 3 个 target, 指标数在千级< / td > < td > 按 series 计费,标签是主要成本< / td > < td > 把 < code > user_id< / code > 、< code > trace_id< / code > 放进标签会让序列数爆炸,内存和查询一起崩< / td > < td > 抓取前用 < code > metricRelabelings< / code > 丢弃高基数标签< / td > < / tr >
< tr > < td > 告警分级与抑制< / td > < td > 一条 warning, 无抑制< / td > < td > P1/P2/P3 分级,上层抑制下层< / td > < td > 数据库挂了会同时触发几十条「接口慢」,不抑制等于没有告警< / td > < td > 在 Alertmanager 配 < code > inhibit_rules< / code > ,按 < code > severity< / code > 与 < code > service< / code > 匹配< / td > < / tr >
< tr > < td > SLO 与错误预算< / td > < td > 阈值 5%,凭经验< / td > < td > 按 SLO 反推阈值与燃烧率< / td > < td > 固定阈值在低流量时误报、高流量时迟钝,预算能把两者统一< / td > < td > 用 1h/6h 双窗口燃烧率替代裸阈值< / td > < / tr >
< tr > < td > 保留期< / td > < td > 6 小时< / td > < td > 本地 15 天,长期下沉对象存储< / td > < td > 本地盘是有限的,容量规划要按天算< / td > < td > 按 < code > retention< / code > 与磁盘配额一起定,超了先降采样< / td > < / tr >
< / tbody >
< / table >
< / div >
< h3 id = "sec-13-10" > 13.10 清理< / h3 >
< p > 告警与 HPA 可以留着; Prometheus 这套栈占资源多,做完实验建议卸掉。< code > helm uninstall< / code > 不会删 CRD。< / p >
< pre data-lang = "bash" data-name = "卸载本章的观测栈" > # 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< / pre >
< p > 最后一条确认 CRD 还在。要彻底清干净就逐个删掉 < code > servicemonitors< / code > 、< code > prometheusrules< / code > 等 CRD; 只做实验的话留着更方便, 下次装回来不用等重建。< / p >
< h3 id = "sec-13-11" > 13.11 小结与自测< / h3 >
< p class = "take" > < b > 一句话:< / b > 指标先有维度, PromQL 才有的算。< / p >
< p class = "take" > < b > 一句话:< / b > HPA 的分母是 requests, 没有它就没有利用率。< / p >
< p class = "take" > < b > 一句话:< / b > firing 只证明规则成立,收到才算告警。< / p >
< details >
< summary > 自测 3 题(点击展开答案)< / summary >
< p > < b > 概念< / b > : < code > endpoints[].port< / code > 写 < code > 8080< / code > 和写 < code > http< / code > 有什么区别?< br > 答: 前者是端口号, 后者是端口名。Operator 只按名字匹配,写数字时生成不出 target, 也不报错。< / p >
< p > < b > 排错< / b > : HPA 显示 < code > TARGETS 85%/99%< / code > ,副本一直是 3, 正常吗? < br > 答:正常。< code > ceil(3 × 0.85 / 0.99) = 3< / code > ,期望副本没变。要它扩,把目标降到 70 以下。< / p >
< p > < b > 决策< / b > :错误率规则用 2 分钟还是 15 分钟窗口?< br > 答: 2 分钟灵敏但容易抖, 适合严重级别; 15 分钟平滑但会漏掉尖峰,适合容量决策。生产里常见两个窗口各配一条。< / p >
< / details >
< div class = "box tip" >
< span class = "bt" > 延伸挑战( ≤30 分钟)< / span >
< p > 把错误率规则换成 1 小时 / 5 分钟双窗口的燃烧率,看同样的 5xx 压力下两条规则谁先 firing。提示: 慢窗口确认趋势, 快窗口负责及时性。< / p >
< / div >
< h3 id = "sec-13-12" > 13.12 衔接< / h3 >
< p > < b > 回收< / b > :第 7 章的 < code > /metrics< / code > 被你改成了带标签和直方图的版本,也顺带说明探针与指标为何分开:探针答「能不能接流量」,指标答「接得好不好」。< / p >
< p > < b > 钩子< / b > :你已经能扩缩和告警,但发布还是「一次性替换所有副本」。第 14 章用 < code > HTTPRoute< / code > 的 < code > weight< / code > 先把 shop-web 新版本放 10% 流量,出错退回 0; 本章的错误率规则可以当刹车。< / p >
< p > 下一章:< a href = "14-release.html" > 第 14 章 发布策略:滚动、蓝绿、金丝雀< / a > < / p >
< h3 id = "sec-13-13" > 13.13 参考与验证版本< / h3 >
< ul >
< li > < a href = "https://prometheus.io/docs/prometheus/latest/querying/basics/" > Prometheus · Querying basics< / a > : < code > rate< / code > 、窗口与选择器的语义。< / li >
< li > < a href = "https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/" > Prometheus · Alerting rules< / a > : < code > for< / code > 与状态机的官方定义。< / li >
< li > < a href = "https://github.com/prometheus-operator/kube-prometheus" > prometheus-operator/kube-prometheus< / a > : ServiceMonitor 与 PrometheusRule 的 CRD 来源。< / li >
< li > < a href = "https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/" > Kubernetes · Horizontal Pod Autoscaling< / a > :期望副本数的算法与 < code > unknown< / code > 的含义。< / li >
< li > < a href = "https://artifacthub.io/packages/helm/prometheus-community/kube-prometheus-stack" > Artifact Hub · kube-prometheus-stack< / a > : chart 版本与默认镜像。< / li >
< / ul >
< p > 验证版本: 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< / p >
< p > 变更记录: 2026-11-11 首版,对应 chart 93.2.0。< / p >
< / article >
< nav class = "pager" >
< a class = "prev" href = "12-logging.html" > < span class = "k" > ← 上一章< / span > < span class = "v" > 第 12 章 · 日志:从 kubectl logs 到可检索< / span > < / a >
< a class = "next" href = "14-release.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 14 章 · 发布策略:滚动、蓝绿、金丝雀< / span > < / a >
< / nav >
< p class = "foot" >
Kubernetes 专题 · S3 第 13 章 指标、扩缩与告警< br >
< a href = "index.html" > 总目录< / a > · < a href = "../../index.html" > 知识库首页< / a > · < a href = "../../SRE工程师/sre-learning-path/index.html" > SRE 学习路径< / a >
< / p >
< / main >
< / div >
< button id = "toTop" title = "回到顶部" > ↑< / button >
< script src = "assets/doc.js" > < / script >
< script src = "../../assets/back.js" data-portal-back = "knowledge/kubernetes" data-portal-label = "知识库 › Kubernetes 专题知识库" > < / script >
< / body >
< / html >