1|1|
从时序数据库TSDB存储引擎原理到PromQL查询执行计划,深入剖析Prometheus抓取模型、服务发现、远程存储、联邦集群、Recording Rules优化、Grafana Dashboard工程化设计以及Alertmanager告警链路,构建生产级K8s可观测性指标体系。
可观测性(Observability)源自控制论,严格定义为:对于一个系统,如果仅通过其外部输出(不依赖内部状态)就能确定系统任意时刻的内部状态,则该系统是可观测的。在云原生语境下,可观测性由三大支柱构成:
| 支柱 | 数据模型 | 核心特征 | 典型系统 | 解决什么问题 |
|---|---|---|---|---|
| Metrics(指标) | 时序数据点 | 数值化、可聚合、低基数 | Prometheus/VM/TSDB | 系统健康度、容量规划、告警 |
| Logs(日志) | 非结构化/半结构化文本 | 高基数、离散事件 | Loki/Elasticsearch | 故障根因定位、审计 |
| Traces(追踪) | 有向无环图(DAG) | 因果关联、跨度层级 | Jaeger/Tempo | 请求路径分析、瓶颈定位 |
监控(Monitoring)是可观测性的子集——它告诉你系统出了什么问题。可观测性还要告诉你为什么出问题。一个只有Metrics的系统可以做到"发现异常",但无法做到"定位根因",因为Metrics丢失了请求级别的因果关系。真正完整的可观测性需要三支柱协同:Metrics触发告警 → Traces定位瓶颈Span → Logs查看具体错误信息。
Prometheus采用多维标签模型,每个时间序列由指标名称和一组标签键值对唯一标识:
# 一个时间序列的形式化定义:
# series = {__name__, label_set} × timestamp → value
#
# 例如:HTTP请求延迟指标
http_request_duration_seconds{method="POST", path="/api/v1/orders", status="200", le="0.1"} 0.95 1700000000
# 标签基数(Cardinality)是核心概念:
# - 低基数标签:method(GET/POST/PUT/DELETE,~10值)
# - 高基数标签:user_id(百万级值)、session_id(千万级值)
# - 高基数标签会导致TSDB中序列爆炸,是Prometheus的头号性能杀手
# 指标类型:
# 1. Counter(只增不减) → http_requests_total
# 2. Gauge(可增可减) → memory_usage_bytes
# 3. Histogram(分桶统计) → http_request_duration_seconds_bucket
# 4. Summary(客户端分位数)→ http_request_duration_seconds{quantile="0.99"}
| 维度 | Pull模型(Prometheus) | Push模型(StatsD/InfluxDB) |
|---|---|---|
| 数据流向 | Server主动拉取Target的/metrics端点 | Agent主动推送数据到Server |
| 服务发现 | 原生支持K8s SD,自动发现Target | 需额外配置Agent注册机制 |
| 健康检测 | 抓取失败即知Target不可达 | 无数据推送即可能不可达,需额外心跳 |
| 负载控制 | Server控制抓取频率,可限流 | Agent控制推送频率,Server被动承受 |
| 短生命周期Job | 需Pushgateway中转(反模式) | 天然支持 |
| 安全性 | Server需能访问所有Target(网络策略复杂) | Agent只需访问Server(网络策略简单) |
| 水平扩展 | 困难(每个Server抓取独立Target集) | 容易(Server无状态,负载均衡即可) |
| 多租户 | 不原生支持(需Thano/Cortex层) | 部分系统原生支持(InfluxDB) |
Pull模型像体检中心主动预约患者——中心控制检查节奏,患者没来就知道异常了。Push模型像患者主动报告症状——患者想什么时候报告就什么时候报告,中心被动接收,但患者不报告时你不知道他是健康还是已经失联。
Prometheus TSDB是受Facebook Gorilla论文启发的列式时序存储引擎。理解其内部结构对于容量规划和性能调优至关重要:
# 一个Block的磁盘布局(默认2小时一个Block):
data/
├── 01HKEJ.../ # Block目录(ULID命名)
│ ├── chunks/ # 数据块目录
│ │ ├── 000001 # 每个Chunk最大120个数据点
│ │ └── 000002
│ ├── index # 倒排索引:label → series_id
│ ├── meta.json # Block元数据(时间范围、统计)
│ └── tombstones # 删除标记(延迟删除)
│
# Chunk内部编码(Gorilla压缩):
# - Timestamps: DoubleDelta编码
# t1=100, t2=104, t3=108, t4=112
# delta1=4, delta2=4, delta3=4
# delta_of_delta=0,0,0 → 每个只占1 bit
# - Values: XOR编码
# 只存与前一个值XOR后的不同bit位
# 适合缓慢变化的指标(如CPU使用率)
# 压缩效果:
# 原始8 bytes/timestamp + 8 bytes/value = 16 bytes/point
# Gorilla压缩后平均 ~1.37 bytes/point
# 压缩比约 12:1
| 存储层级 | 位置 | 时间范围 | 编码方式 | 查询特性 |
|---|---|---|---|---|
| Head Block | 内存+mmap | 最近~2h | Chunk(DoubleDelta+XOR) | 最新数据,查询最快 |
| Compacted Block | 磁盘 | 2h~retention | Chunk+倒排索引 | 历史数据,需加载索引 |
| WAL | 磁盘顺序写 | 最近~2h | 原始未压缩 | 崩溃恢复用,不查询 |
| mmap chunks | 内存映射文件 | Head中较旧Chunk | Chunk压缩 | 内存压力大时自动落盘 |
TSDB的倒排索引将标签值映射到Series ID集合。当标签基数过高时,索引膨胀导致内存和查询性能问题:
// Prometheus TSDB倒排索引核心结构
type Index struct {
// 标签名+值 → Postings列表(Series ID有序集合)
postings map[string]Postings // key = "method\x00POST"
// Series ID → 标签集
series map[uint64]labels.Labels
// 符号表(字符串去重)
symbols *Symbols // 所有标签名/值去重存储
}
// 查询 http_requests_total{method="POST",status="200"} 的过程:
// 1. postings["__name__\x00http_requests_total"] → P1
// 2. postings["method\x00POST"] → P2
// 3. postings["status\x00200"] → P3
// 4. result = P1 ∩ P2 ∩ P3 (Postings交集,归并排序)
// 5. 对每个Series ID,从chunks中加载数据点
// 高基数问题:
// 如果 user_id 有 1,000,000 个不同值
// 则 postings["user_id\x00xxx"] 有 1,000,000 个条目
// 每个条目至少 8 bytes (uint64) → 8MB 仅一个标签
// 100个高基数标签 → 800MB 纯索引开销
某团队将request_id(UUID,每次请求唯一)作为Prometheus指标标签,导致单实例在2小时内产生超过200万条时间序列,内存从2GB暴涨至16GB后OOM。正确做法:request_id应放在Logs/Traces中,不应出现在Metrics标签中。Prometheus指标标签只应包含低基数的分类维度(method、status、service名等)。
Prometheus的Kubernetes SD通过Watch K8s API Server来动态发现监控目标。理解其发现逻辑对于正确配置监控至关重要:
# Prometheus通过K8s API发现目标的配置
scrape_configs:
# 1. 监控kubelet(直接访问节点)
- job_name: 'kubelet'
kubernetes_sd_configs:
- role: node # 发现集群所有Node
scheme: https
tls_config:
cert_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
insecure_skip_verify: true
bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
relabel_configs:
# 将 __address__ 从默认的10250改为10255(cAdvisor)
- action: replace
source_labels: [__address__]
regex: ([^:]+)(?::\d+)?
replacement: $1:10255
target_label: __address__
# 添加节点名标签
- action: labelmap
regex: __meta_kubernetes_node_label_(.+)
# 2. 监控Pod(通过annotations标记)
- job_name: 'kubernetes-pods'
kubernetes_sd_configs:
- role: pod # 发现所有Pod
relabel_configs:
# 只抓取有 prometheus.io/scrape=true 注解的Pod
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
# 使用注解中指定的端口
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
target_label: __address__
# 映射Pod标签到Prometheus标签
- action: labelmap
regex: __meta_kubernetes_pod_label_(.+)
# 添加namespace和pod名标签
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod
# 3. 监控Service(通过annotations标记)
- job_name: 'kubernetes-services'
kubernetes_sd_configs:
- role: service
relabel_configs:
- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape]
action: keep
regex: true
# 只抓取有端口的Service
- source_labels: [__meta_kubernetes_service_port_name]
action: keep
regex: .+
| Role | 发现对象 | __address__来源 | 典型场景 | 元数据标签 |
|---|---|---|---|---|
| node | 集群所有Node | Node InternalIP:10250 | 监控kubelet/cAdvisor | __meta_kubernetes_node_* |
| pod | 所有Pod的所有容器 | PodIP:containerPort | 应用自定义指标 | __meta_kubernetes_pod_* |
| service | 所有Service | ClusterIP:servicePort | 通过Service负载均衡抓取 | __meta_kubernetes_service_* |
| endpoints | 所有Endpoint | EndpointIP:port | 直连后端Pod,绕过Service | __meta_kubernetes_endpoint_* |
对于应用指标监控,优先使用role: pod而非role: service。原因:Service通过kube-proxy负载均衡,抓取到的指标是随机某个Pod的,无法区分具体是哪个Pod的指标。而role: pod会为每个Pod生成独立的Target,指标中带有pod标签,可以精确定位到具体Pod。role: endpoints适合需要绕过Service直接抓取后端Pod的场景(如gRPC服务,Service负载均衡可能不准确)。
Relabel是Prometheus SD中最强大也最容易被误解的机制。它在Target被发现后、抓取前对标签进行重写:
relabel_configs:
# 1. keep: 只保留匹配的Target(过滤)
- source_labels: [__meta_kubernetes_namespace]
action: keep
regex: (production|staging) # 只监控prod和staging命名空间
# 2. drop: 丢弃匹配的Target
- source_labels: [__meta_kubernetes_pod_label_monitoring_exclude]
action: drop
regex: true # 排除标记了不监控的Pod
# 3. replace: 替换标签值(最常用)
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod
replacement: $1 # 将Pod名赋值给pod标签
# 4. labelmap: 批量映射标签名
- action: labelmap
regex: __meta_kubernetes_pod_label_(.+)
# 将所有 __meta_kubernetes_pod_label_xxx 映射为 xxx
# 5. labeldrop: 删除标签
- action: labeldrop
regex: __meta_kubernetes_pod_label_(.+) # 清理中间标签
# 6. hashmod: 一致性哈希(用于分片)
- source_labels: [__address__]
target_label: __tmp_hash
modulus: 4 # 4个Prometheus分片
action: hashmod
- source_labels: [__tmp_hash]
action: keep
regex: 0 # 这个实例只抓取hash=0的Target
PromQL有四种数据类型,理解它们是编写正确查询的基础:
| 类型 | 定义 | 示例 | 说明 |
|---|---|---|---|
| Instant Vector | 同一时间戳的多个序列 | http_requests_total | 最常用,返回每个序列最新值 |
| Range Vector | 一段时间范围内的序列 | http_requests_total[5m] | 只能用于rate/avg_over_time等函数 |
| Scalar | 单个数值 | 1024 或 count(up) | 用于算术运算 |
| String | 字符串字面量 | "hello" | 仅用于info()等少量场景 |
这三个函数是处理Counter类型指标最常用的函数,但它们的计算逻辑截然不同:
# 假设 [5m] 范围内有6个数据点:
# t0=0:00 v=100
# t1=1:00 v=120
# t2=2:00 v=150
# t3=3:00 v=180
# t4=4:00 v=200
# t5=5:00 v=250
# rate(v[5m]) —— 平均增长率
# 计算: (v_last - v_first) / (t_last - t_first)
# = (250 - 100) / (300 - 0) = 150/300 = 0.5/s
# 特点: 平滑,适合告警和长期趋势
# 注意: 会自动处理Counter重置(值下降时认为重置过)
# irate(v[5m]) —— 瞬时增长率
# 计算: (v_last - v_prev) / (t_last - t_prev)
# = (250 - 200) / (300 - 240) = 50/60 = 0.83/s
# 特点: 灵敏,适合绘制实时图表
# 注意: 只用最后两个点,波动大,不适合告警
# increase(v[5m]) —— 5分钟内总增量
# 计算: (v_last - v_first) = 250 - 100 = 150
# 特点: 返回绝对增量而非速率
# 注意: 会做外推(extrapolation)校正,结果可能略大于实际增量
# ⚠️ 常见错误:用 increase 统计"5分钟内请求数"
# 正确做法:increase 会做外推,如果抓取间隔不整除5m会有偏差
# 更准确的做法:sum(rate(http_requests_total[5m])) * 300
| 函数 | 计算方式 | 数据点使用 | 适用场景 | 注意事项 |
|---|---|---|---|---|
| rate() | (末值-首值)/时间范围 | 全部点 | 告警、长期趋势图 | 平滑,延迟感知低 |
| irate() | (末值-倒数第二值)/间隔 | 最后2个点 | 实时图表、瞬时变化 | 波动大,不适合告警 |
| increase() | 末值-首值(含外推) | 全部点 | 统计区间内总量 | 外推可能导致非整数 |
| deriv() | 线性回归斜率 | 全部点 | 预测趋势 | 适合Gauge类型 |
| predict_linear() | 线性回归预测 | 全部点 | 容量预测告警 | 预测磁盘满等 |
# 指标: http_requests_total{method, status, namespace, pod}
# 1. sum by —— 按指定标签分组聚合
sum by (namespace) (rate(http_requests_total[5m]))
# 结果: {namespace="default"} 0.5, {namespace="prod"} 1.2
# 2. sum without —— 保留指定标签,聚合其余所有标签
sum without (pod) (rate(http_requests_total[5m]))
# 结果保留 method, status, namespace,聚合掉pod维度
# 3. ⚠️ sum vs sum by —— 最常见的错误
sum(rate(http_requests_total[5m]))
# 这会把所有序列的rate加在一起,结果只有一个值
# 丢失了所有标签维度,通常不是你想要的!
# 4. 多级聚合
sum by (namespace) (
sum by (namespace, pod) (
rate(http_requests_total[5m])
)
)
# 先按namespace+pod聚合,再按namespace聚合
# 5. topk —— 找出最高/最低的N个序列
topk(5, sum by (pod) (rate(http_requests_total[5m])))
# 找出QPS最高的5个Pod
# 6. quantile —— 计算分位数
quantile(0.99, http_request_duration_seconds)
# ⚠️ 这是客户端分位数,在多个Pod间不可加!
# 跨Pod聚合分位数的正确方式见下文Histogram
延迟监控是可观测性最核心的需求之一,但分位数聚合是一个容易出错的地方:
# Histogram指标在Prometheus中存储为3个序列:
# http_request_duration_seconds_bucket{le="0.1"} # ≤0.1s的请求计数
# http_request_duration_seconds_bucket{le="0.5"} # ≤0.5s的请求计数
# http_request_duration_seconds_bucket{le="+Inf"} # 总请求数
# http_request_duration_seconds_sum # 延迟总和
# http_request_duration_seconds_count # 请求计数
# ❌ 错误:直接对Summary的quantile标签做avg
# avg by (namespace) (http_request_duration_seconds{quantile="0.99"})
# 这计算的是"各Pod P99的平均值",不是"全局P99"
# 数学上 avg(P99_i) ≤ P99(合并),这个值会偏低
# ✅ 正确:用histogram_quantile聚合Histogram
histogram_quantile(0.99,
sum by (le) (rate(http_request_duration_seconds_bucket[5m]))
)
# 步骤:
# 1. rate() 计算每个bucket的增长率
# 2. sum by (le) 将所有Pod的同一bucket累加
# 3. histogram_quantile 在累加后的bucket上插值计算P99
# 跨namespace的P99延迟:
histogram_quantile(0.99,
sum by (le, namespace) (rate(http_request_duration_seconds_bucket[5m]))
)
# Apdex score(应用性能指数):
(
sum(rate(http_request_duration_seconds_bucket{le="0.1"}[5m])) # 满意
+ 0.5 * sum(rate(http_request_duration_seconds_bucket{le="0.5"}[5m])
- rate(http_request_duration_seconds_bucket{le="0.1"}[5m])) # 可容忍
) / sum(rate(http_request_duration_seconds_count[5m])) # 总请求
bucket边界le的设计直接决定分位数计算的精度。如果P99落在两个bucket之间,histogram_quantile会做线性插值,插值误差取决于bucket间距。生产建议:在SLA边界附近密集分桶,远离SLA的区间稀疏分桶。例如,如果SLA是200ms,bucket设计为[5, 10, 25, 50, 100, 150, 200, 250, 300, 500, 1000, +Inf],在200ms附近密集分桶。避免+Inf作为唯一大桶,否则高延迟请求的精确值完全丢失。
# 1. 子查询:在查询中嵌入range查询
# 计算"过去1小时每5分钟的QPS"的变化趋势
max_over_time(
sum by (namespace) (rate(http_requests_total[5m]))[1h:5m]
)
# [1h:5m] 表示过去1小时,每5分钟采样一次
# 2. @修饰符:偏移到特定时间点
# 查看一周前同一时刻的QPS
rate(http_requests_total[5m] @ end() - 7d)
# # 3. 对比当前与上周(环比)
rate(http_requests_total[5m])
/ on(namespace) group_left
rate(http_requests_total[5m] offset 7d)
# 结果 > 1 表示QPS比上周高
# 4. label_replace:动态修改标签
label_replace(
up{job="kubernetes-pods"},
"service",
"$1",
"pod",
"(.*)-.*-.*"
)
# 从pod名 "order-service-xxx-yyy" 提取 "order-service" 作为service标签
# 5. clamp_min/clamp_max:防止除零和异常值
clamp_min(
rate(http_requests_total[5m]) / on(namespace) group_left rate(http_errors_total[5m]),
0
)
Prometheus单实例存在两个根本限制:无水平扩展(单实例抓取的Target集固定)和无持久化HA(本地TSDB无副本)。生产环境必须解决这两个问题:
| 方案 | HA能力 | 扩展能力 | 架构复杂度 | 适用规模 |
|---|---|---|---|---|
| 联邦(Federation) | 部分 | 好 | 低 | 中小规模(<100节点/实例) |
| Thanos | 完整 | 优秀 | 中 | 大规模(数百~数千节点) |
| Cortex/Mimir | 完整 | 优秀 | 高 | 超大规模/多租户 |
| VictoriaMetrics | 完整 | 优秀 | 低 | 大规模(轻量替代) |
# 下层Prometheus(分片抓取,每个负责一部分Target)
# 通过hashmod分片,4个实例各抓取1/4的Target
scrape_configs:
- job_name: 'kubernetes-pods'
kubernetes_sd_configs:
- role: pod
relabel_configs:
# 一致性哈希分片
- source_labels: [__address__]
target_label: __tmp_hash
modulus: 4
action: hashmod
- source_labels: [__tmp_hash]
action: keep
regex: "0" # 实例0只抓取hash%4==0的Target
# 上层联邦Prometheus(聚合全局视图)
scrape_configs:
- job_name: 'federate'
scrape_interval: 30s
scrape_timeout: 25s
static_configs:
- targets:
- prometheus-0.prometheus:9090
- prometheus-1.prometheus:9090
- prometheus-2.prometheus:9090
- prometheus-3.prometheus:9090
metrics_path: '/federate'
params:
'match[]':
# 只联邦聚合后的指标(Recording Rules结果)
- '{__name__=~"job:.*"}'
- '{__name__="up"}'
# 不要联邦原始高基数指标!
联邦的match[]如果配置为{__name__=~".*"}(联邦所有指标),上层Prometheus会抓取所有下层的原始序列,导致上层内存爆炸。正确做法:下层Prometheus通过Recording Rules预聚合高基数指标,联邦只抓取预聚合后的低基数结果。例如下层计算job:http_requests:rate5m,联邦只抓取这个聚合指标。
# Thanos Sidecar与Prometheus同Pod部署
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: prometheus
spec:
template:
spec:
containers:
- name: prometheus
image: prom/prometheus:v2.48.0
args:
- --storage.tsdb.path=/data
- --storage.tsdb.retention.time=24h # 本地只保留24h
- --storage.tsdb.min-block-duration=2h
- --storage.tsdb.max-block-duration=2h
# 必须设置min=max=2h,否则Sidecar无法上传
volumeMounts:
- name: data
mountPath: /data
- name: thanos-sidecar
image: thanosio/thanos:v0.32.5
args:
- sidecar
- --tsdb.path=/data
- --prometheus.url=http://localhost:9090
- --objstore.config-file=/etc/thanos/objstore.yaml
# Sidecar定期检查/data中的已完成Block,上传到对象存储
# 上传后在本地标记.meta.json中添加thanos标志
volumeMounts:
- name: data
mountPath: /data
- name: thanos-config
mountPath: /etc/thanos
volumes:
- name: thanos-config
configMap:
name: thanos-objstore
---
# 对象存储配置(S3示例)
apiVersion: v1
kind: ConfigMap
metadata:
name: thanos-objstore
data:
objstore.yaml: |
type: S3
config:
bucket: "thanos-metrics"
endpoint: "s3.us-east-1.amazonaws.com"
access_key: "AKIAXXXX"
secret_key: "xxxxx"
sse_config:
type: SSE-KMS
Thanos Query是全局查询入口,它通过Store API从多个数据源(Sidecar、Store Gateway、Receiver)拉取数据,并执行跨实例去重:
apiVersion: apps/v1
kind: Deployment
metadata:
name: thanos-query
spec:
template:
spec:
containers:
- name: thanos-query
image: thanosio/thanos:v0.32.5
args:
- query
- --http-address=0.0.0.0:19192
- --grpc-address=0.0.0.0:10901
# 数据源端点(通过gRPC连接)
- --endpoint=thanos-sidecar-grpc:10901 # 实时数据
- --endpoint=thanos-store-gateway:10901 # 历史数据
- --endpoint=thanos-receiver:10901 # 远程写入数据
# 去重配置(HA Prometheus副本去重)
- --query.replica-label=prometheus_replica
# 查询优化
- --query.max-concurrent=20
- --query.timeout=30s
# 自动降采样:大时间范围用5m/1h降采样数据
- --query.auto-downsampling
---
# Grafana数据源配置:指向Thanos Query
apiVersion: v1
kind: ConfigMap
metadata:
name: grafana-datasources
data:
datasources.yaml: |
apiVersion: 1
datasources:
- name: Thanos
type: prometheus
url: http://thanos-query:19192
isDefault: true
jsonData:
timeInterval: "30s"
Grafana是可观测性可视化的事实标准。理解其架构有助于设计高效的Dashboard:
支持Prometheus、Loki、Tempo、Jaeger、Elasticsearch、MySQL等30+数据源。每个数据源有专属的查询构建器和变量支持。通过proxy模式转发查询,避免CORS问题。
Time Series、Stat、Gauge、Bar Gauge、Heatmap、Node Graph、Geo Map等。每个面板绑定一个数据源查询,支持阈值着色、Annotations标注、数据转换。
Dashboard参数化:通过变量动态过滤查询(如选择namespace、pod)。变量可从数据源查询中动态获取值,支持级联过滤。
Grafana 8+统一告警引擎,支持跨数据源告警规则。告警规则绑定到Folder,通过Contact Point分发通知。
# 变量1: namespace(从Prometheus查询所有namespace)
# Type: Query
# Data source: Thanos
# Query: label_values(kube_pod_info, namespace)
# 变量2: pod(依赖namespace变量,级联过滤)
# Type: Query
# Query: label_values(kube_pod_info{namespace="$namespace"}, pod)
# 变量3: container(依赖namespace和pod)
# Type: Query
# Query: label_values(kube_pod_container_info{namespace="$namespace", pod="$pod"}, container)
# 变量4: datasource(多数据源切换)
# Type: Datasource
# Plugin: Prometheus
# 面板查询中使用变量:
# rate(container_cpu_usage_seconds_total{namespace="$namespace", pod="$pod", container="$container"}[5m])
# / on(container, pod, namespace) group_left
# kube_pod_container_resource_limits{resource="cpu"}
| 面板类型 | 适用场景 | 最佳实践 | 常见错误 |
|---|---|---|---|
| Time Series | 时序曲线 | 用Legend别名,限制序列数<10 | 不设Legend导致{{labels}}显示原始标签 |
| Stat | 单值KPI | 设阈值着色,用后缀单位 | 显示过多Stat导致信息过载 |
| Gauge | 百分比/利用率 | 设Min/Max和阈值区间 | 未设Max导致指针位置无意义 |
| Heatmap | 延迟分布 | 配合Histogram bucket数据 | 用Summary的quantile做Heatmap(数据点太少) |
| Bar Gauge | 多维度排名 | 按值排序,限制显示数量 | 不排序导致最重要的值在底部 |
| Node Graph | 服务拓扑图 | 节点数<50,否则性能差 | 数百节点导致浏览器卡死 |
# 1. Grafana Provisioning配置
apiVersion: v1
kind: ConfigMap
metadata:
name: grafana-provisioning
data:
dashboards.yaml: |
apiVersion: 1
providers:
- name: 'gitops-dashboards'
orgId: 1
folder: 'Kubernetes'
folderUid: k8s-folder
type: file
disableDeletion: false
updateIntervalSeconds: 30
allowGrafanaOverwrite: true
options:
path: /var/lib/grafana/dashboards
# 2. Dashboard JSON通过ConfigMap挂载
---
apiVersion: v1
kind: ConfigMap
metadata:
name: dashboard-k8s-overview
labels:
grafana_dashboard: "1" # grafana-watcher自动发现
data:
k8s-overview.json: |
{
"title": "Kubernetes Cluster Overview",
"templating": {
"list": [
{
"name": "namespace",
"type": "query",
"datasource": "Thanos",
"query": "label_values(kube_pod_info, namespace)"
}
]
},
"panels": [
{
"type": "stat",
"title": "Pod总数",
"targets": [{
"expr": "sum(kube_pod_info{namespace=\"$namespace\"})"
}]
}
]
}
# 3. 用grafana-watcher或Argo CD同步Dashboard
# grafana-watcher监听ConfigMap变化,自动导入/更新Dashboard
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: grafana-watcher
spec:
template:
spec:
containers:
- name: grafana-watcher
image: quay.io/coreos/grafana-watcher:v0.0.8
args:
- --grafana-url=http://grafana:3000
- --watch-dir=/var/lib/grafana/dashboards
# 告警在Prometheus中的生命周期:
#
# [inactive] ──条件满足──> [pending] ──for持续时间──> [firing] ──发送到Alertmanager──> [resolved]
# ↑ ↑ │
# └──────────────────────────┴──────────────── 条件不满足 ────────────────────┘
#
# pending: 条件已满足但还未达到for指定的时间,不发送通知
# firing: 条件满足且持续了for指定的时间,发送到Alertmanager
# resolved: 条件不再满足,Alertmanager发送恢复通知
#
# Alertmanager侧状态:
# [received] → [grouped] → [inhibited] → [silenced] → [sent]
#
# grouping: 将相同标签的告警合并为一个通知
# inhibition: 高级别告警抑制同源低级别告警
# silence: 人工静音,时间段内不发送指定标签的告警
groups:
- name: kubernetes-node
rules:
# 1. 节点NotReady告警
- alert: NodeNotReady
expr: kube_node_status_condition{condition="Ready", status="unknown"} == 1
for: 5m # 持续5分钟才告警,避免抖动
labels:
severity: critical
team: sre
annotations:
summary: "Node {{ $labels.node }} is not ready"
description: "Node {{ $labels.node }} has been unready for more than 5 minutes."
runbook: "https://wiki.example.com/runbooks/node-not-ready"
# 2. CPU高使用率告警(多维度)
- alert: NodeCPUHigh
expr: |
100 - (avg by (node) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 85
for: 10m
labels:
severity: warning
team: sre
annotations:
summary: "Node {{ $labels.node }} CPU usage is high"
description: "CPU usage is {{ $value | humanize }}% on node {{ $labels.node }}"
# 3. Pod重启告警
- alert: PodRestarting Frequently
expr: increase(kube_pod_container_status_restarts_total[1h]) > 5
for: 0m # 立即告警
labels:
severity: warning
team: app
annotations:
summary: "Pod {{ $labels.namespace }}/{{ $labels.pod }} restarting frequently"
description: "Pod has restarted {{ $value }} times in the last hour."
# 4. 磁盘即将满(预测性告警)
- alert: NodeDiskWillFillIn24h
expr: |
predict_linear(node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"}[6h], 24 * 3600) < 0
for: 1h
labels:
severity: critical
team: sre
annotations:
summary: "Disk on {{ $labels.node }} will fill in 24h"
description: "Based on current trend, {{ $labels.mountpoint }} will be full in 24 hours."
| 设计原则 | 说明 | 示例 |
|---|---|---|
| for延迟 | 避免瞬时抖动误报 | CPU高使用率for: 10m,不用for: 0m |
| 分级severity | 区分critical/warning/info | critical打电话,warning发Slack,info仅记录 |
| runbook链接 | annotation中附处理手册URL | 告警自带处理步骤,降低MTTR |
| 避免基数 | 告警标签不要用高基数标签 | 用node而非pod IP,用namespace而非pod名 |
| 对称告警 | 有告警就要有恢复通知 | Alertmanager自动发resolve通知 |
| 预测性告警 | 在问题发生前预警 | predict_linear预测磁盘满、内存OOM |
global:
resolve_timeout: 5m # 告警恢复后5分钟发送resolve通知
route:
group_by: ['alertname', 'namespace', 'cluster'] # 按这些标签分组
group_wait: 30s # 首次告警等待30s,收集同组告警
group_interval: 5m # 同组告警下次发送间隔
repeat_interval: 4h # 未恢复告警重复发送间隔
receiver: 'default' # 默认接收者
routes:
# critical告警 → PagerDuty + Slack
- matchers: ['severity="critical"']
receiver: 'pagerduty-critical'
group_wait: 0s # critical立即发送
repeat_interval: 1h
continue: true # 继续匹配后续路由
- matchers: ['severity="critical"']
receiver: 'slack-critical'
# warning告警 → Slack
- matchers: ['severity="warning"']
receiver: 'slack-warning'
# 按团队路由
- matchers: ['team="app"']
receiver: 'slack-app-team'
inhibit_rules:
# 节点NotReady时,抑制该节点上的所有Pod告警
- source_matchers: ['alertname="NodeNotReady"']
target_matchers: ['alertname=~"Pod.*"']
equal: ['node']
# 集群不可用时,抑制所有集群内告警
- source_matchers: ['alertname="ClusterDown"']
target_matchers: ['cluster=~".*"']
equal: ['cluster']
receivers:
- name: 'pagerduty-critical'
pagerduty_configs:
- routing_key: 'xxxxx'
severity: 'critical'
description: '{{ .CommonAnnotations.summary }}'
- name: 'slack-critical'
slack_configs:
- api_url: 'https://hooks.slack.com/services/xxx'
channel: '#alerts-critical'
title: '[{{ .Status | toUpper }}] {{ .CommonLabels.alertname }}'
text: '{{ range .Alerts }}{{ .Annotations.description }}\n{{ end }}'
使用社区维护的kube-prometheus-stack Chart,它打包了Prometheus Operator、Grafana、Alertmanager、Node Exporter和kube-state-metrics。
# 添加Prometheus社区Helm仓库
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
# 创建监控命名空间
kubectl create namespace monitoring
# 生成values文件进行定制
cat > prom-values.yaml << 'EOF'
prometheus:
prometheusSpec:
replicas: 2 # HA: 2个Prometheus副本
retention: 7d # 本地保留7天
retentionSize: "50GB" # 或按大小限制
storageSpec:
volumeClaimTemplate:
spec:
storageClassName: gp3
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 50Gi
resources:
requests:
memory: 4Gi
cpu: 2
limits:
memory: 8Gi
cpu: 4
# 启用Thanos Sidecar
thanos:
image: thanosio/thanos:v0.32.5
objectStorageConfig:
key: objstore.yaml
name: thanos-objstore
# 附加Scrape配置
additionalScrapeConfigs:
- job_name: 'kubernetes-pods-app'
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
grafana:
adminPassword: "secure-password-change-me"
persistence:
enabled: true
size: 10Gi
datasources:
datasources.yaml:
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
url: http://prometheus-operated:9090
isDefault: true
alertmanager:
config:
route:
group_by: ['alertname', 'namespace']
group_wait: 30s
receiver: 'slack-default'
receivers:
- name: 'slack-default'
slack_configs:
- api_url: 'https://hooks.slack.com/services/xxx'
channel: '#alerts'
EOF
# 安装
helm install kube-prom prometheus-community/kube-prometheus-stack \
-n monitoring -f prom-values.yaml
# 检查所有Pod
kubectl get pods -n monitoring
# NAME READY STATUS
# alertmanager-kube-prom-alertmanager-0 2/2 Running
# grafana-xxx 1/1 Running
# prometheus-kube-prom-prometheus-0 2/2 Running
# prometheus-kube-prom-prometheus-1 2/2 Running
# kube-prom-prometheus-node-exporter-xxx 1/1 Running
# kube-state-metrics-xxx 1/1 Running
# 检查Prometheus抓取状态
kubectl port-forward -n monitoring svc/kube-prom-prometheus 9090:9090
# 浏览器打开 http://localhost:9090/targets
# 确认所有job都是UP状态
# 检查抓取的Target数量
curl -s http://localhost:9090/api/v1/targets | jq '.data.activeTargets | length'
# 期望输出: 50+ (取决于集群规模)
# 检查时间序列数量
curl -s 'http://localhost:9090/api/v1/series?match[]={__name__=~".+"}' | jq '.data | length'
# 期望输出: 10000+ (正常集群)
# Python应用使用prometheus_client暴露指标
from prometheus_client import Counter, Histogram, generate_latest
from flask import Flask, Response
import time, random
app = Flask(__name__)
# 定义指标
REQUEST_COUNT = Counter(
'http_requests_total',
'Total HTTP requests',
['method', 'endpoint', 'status']
)
REQUEST_LATENCY = Histogram(
'http_request_duration_seconds',
'HTTP request latency',
['method', 'endpoint'],
buckets=[0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, float('inf')]
)
@app.before_request
def before_request():
request.start_time = time.time()
@app.after_request
def after_request(response):
latency = time.time() - request.start_time
REQUEST_COUNT.labels(
method=request.method,
endpoint=request.path,
status=str(response.status_code)
).inc()
REQUEST_LATENCY.labels(
method=request.method,
endpoint=request.path
).observe(latency)
return response
@app.route('/metrics')
def metrics():
return Response(generate_latest(), mimetype='text/plain')
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-service
spec:
template:
metadata:
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/metrics"
spec:
containers:
- name: app
image: order-service:latest
ports:
- containerPort: 8080
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: recording-rules
namespace: monitoring
spec:
groups:
- name: k8s-recording
interval: 30s # 每30秒预计算一次
rules:
# 预计算容器CPU使用率
- record: container:cpu_usage:rate5m
expr: |
sum by (namespace, pod, container) (
rate(container_cpu_usage_seconds_total[5m])
)
# 预计算容器CPU使用率占Limit百分比
- record: container:cpu_usage:ratio
expr: |
container:cpu_usage:rate5m
/ on(namespace, pod, container) group_left
kube_pod_container_resource_limits{resource="cpu"}
# 预计算namespace级别QPS
- record: namespace:http_requests:rate5m
expr: |
sum by (namespace, method, status) (
rate(http_requests_total[5m])
)
# 预计算P99延迟(跨Pod聚合)
- record: namespace:http_latency:p99
expr: |
histogram_quantile(0.99,
sum by (namespace, endpoint, le) (
rate(http_request_duration_seconds_bucket[5m])
)
)
# 查询应用QPS
curl -s -G http://localhost:9090/api/v1/query \
--data-urlencode 'query=sum by (namespace) (rate(http_requests_total[5m]))' | jq '.data.result'
# 期望输出: [{ "metric": {"namespace": "default"}, "value": [1700000000, "2.5"] }]
# 查询P99延迟
curl -s -G http://localhost:9090/api/v1/query \
--data-urlencode 'query=namespace:http_latency:p99{namespace="default"}' | jq '.data.result'
# 期望输出: [{ "value": [1700000000, "0.15"] }] # P99 = 150ms
# 查询CPU使用率最高的Pod
curl -s -G http://localhost:9090/api/v1/query \
--data-urlencode 'query=topk(5, container:cpu_usage:ratio)' | jq '.data.result'
# 期望输出: CPU使用率最高的5个容器
# 打开Grafana验证Dashboard
kubectl port-forward -n monitoring svc/kube-prom-grafana 3000:80
# 浏览器打开 http://localhost:3000 (admin/secure-password-change-me)
某电商平台K8s集群从200节点扩展到2000节点后,Prometheus单实例内存从8GB增长到32GB,频繁OOM重启。抓取间隔15s,每秒抓取约4000个Target,产生约80万条时间序列。
| 优化措施 | 效果 | 具体操作 | 原理 |
|---|---|---|---|
| 分片抓取 | 内存降60% | 4个Prometheus实例hashmod分片 | 每实例只抓1/4 Target,序列数1/4 |
| Recording Rules | 查询加速10x | 预聚合高频查询为新指标 | 查询从扫描80万序列变为读取预计算结果 |
| 减少抓取频率 | 内存降20% | 非关键指标从15s改为30s/60s | 序列数据点密度减半,Chunk更少 |
| 标签精简 | 内存降15% | 移除pod IP、container ID等高基数标签 | 减少序列总数和索引开销 |
| 启用mmap | 内存降30% | --storage.tsdb.mmap-chunks=true | 旧Chunk映射到文件,不占堆内存 |
| Thanos远程存储 | 本地内存降40% | 本地retention从7d降为24h | 历史数据上传S3,本地只留最新 |
某次集群网络抖动导致200个Pod同时重启,触发200条PodRestart告警 + 50条ServiceUnavailable告警 + 30条ProbeFailed告警,共计280条告警在1分钟内涌入Slack,导致告警通道被淹没,重要告警被忽略。
# 1. 告警分组:将同类告警合并为一个通知
route:
group_by: ['alertname', 'namespace'] # 同名+同namespace的告警合并
group_wait: 2m # 等2分钟收集同组告警
group_interval: 10m # 同组新增告警10分钟后才追加发送
# 2. 抑制规则:高优先级告警抑制低优先级
inhibit_rules:
# 节点NotReady时,抑制该节点上所有Pod告警
- source_matchers: ['alertname="NodeNotReady"']
target_matchers: ['alertname=~"Pod.*|Container.*"']
equal: ['node']
# 集群级别告警抑制所有命名空间级别告警
- source_matchers: ['severity="cluster-critical"']
target_matchers: ['severity=~"warning|critical"']
# 3. 告警聚合规则:用PromQL将多Pod告警聚合为一条
- alert: PodBatchRestart
expr: |
count(
increase(kube_pod_container_status_restarts_total[1h]) > 5
) by (namespace) > 3
# 只有同一namespace中超过3个Pod在重启才告警
# 告警内容包含重启Pod数量而非逐个列出
annotations:
summary: "{{ $value }} pods restarting in namespace {{ $labels.namespace }}"
description: "More than 3 pods are restarting frequently in {{ $labels.namespace }}"
# 4. 临时静音:已知问题维护期间
# amtool silence add --comment="网络维护" --duration=2h \
# alertname=PodRestarting namespace=default
# 第一层:原始指标聚合(每15s)
# 将高基数原始指标聚合为低基数中间指标
record: container:cpu:rate1m
expr: sum by (namespace, pod, container) (rate(container_cpu_usage_seconds_total[1m]))
# 第二层:业务维度聚合(每30s)
# 按业务维度(service、namespace)聚合
record: service:cpu:rate5m
expr: sum by (namespace, service) (container:cpu:rate1m)
# 第三层:全局聚合(每1m)
# 全局级别聚合,用于Dashboard和告警
record: cluster:cpu:usage:ratio
expr: sum(service:cpu:rate5m) / sum(kube_node_status_allocatable{resource="cpu"})
# 查询时直接使用第三层指标,O(1)复杂度
# 而非每次从80万原始序列实时聚合,O(n)复杂度
| 问题现象 | 诊断命令 | 可能根因 | 解决方案 |
|---|---|---|---|
| Prometheus OOM Killed | kubectl describe pod看OOMKilled;检查prometheus_tsdb_head_series | 时间序列过多(高基数标签) | 移除高基数标签;增加分片;启用mmap |
| Target状态为DOWN | 检查/targets页面;curl target:port/metrics | 网络策略阻止;Pod未暴露/metrics;端口错误 | 检查NetworkPolicy;添加注解;修正relabel端口 |
| 查询超时 | 检查查询时间范围;prometheus_engine_query_duration | 大范围查询扫描过多序列;无Recording Rules | 缩小时间范围;添加Recording Rules;用Thanos降采样 |
| Grafana面板无数据 | 检查数据源连接;在Explore中直接执行查询 | 时间范围不对;变量未选择;查询语法错误 | 调整时间范围;检查变量值;用Explore调试 |
| 告警不触发 | curl /api/v1/alerts看pending/firing状态 | for时间未到;表达式错误;Alertmanager路由不匹配 | 检查alert状态;验证expr;检查route匹配 |
| 告警不发送 | 检查Alertmanager日志;amtool alert | 被inhibit抑制;被silence静音;receiver配置错误 | 检查inhibit/silence;验证receiver URL |
| 磁盘空间满 | df -h;检查prometheus_tsdb_storage_blocks_bytes | retention过长;序列过多;WAL过大 | 缩短retention;增加分片;清理WAL |
| 抓取延迟高 | 检查scrape_duration_seconds指标 | Target过多;网络延迟;/metrics响应慢 | 增加scrape_timeout;分片;优化应用指标暴露 |
| Thanos Sidecar不上传 | 检查Sidecar日志;--debug模式 | 对象存储权限;Block未完成(min≠max duration) | 检查S3权限;设置min=max block duration |
| Thanos Query慢 | 检查Query日志中的store_api调用延迟 | 大范围查询未用降采样;Store Gateway过多 | 启用auto-downsampling;限制查询范围 |
| 命令 | 用途 |
|---|---|
prometheus_tsdb_head_series | 当前活跃时间序列数量(监控基数) |
prometheus_tsdb_head_samples_appended_total | 每秒追加的样本数(吞吐量) |
prometheus_scrape_duration_seconds | 各Target抓取耗时 |
prometheus_scrape_samples_post_metric_relabeling | relabel后保留的样本数 |
prometheus_rule_evaluation_duration_seconds | 规则评估耗时 |
curl localhost:9090/api/v1/status/config | 查看当前生效配置 |
curl localhost:9090/api/v1/targets | 查看所有Target状态 |
curl localhost:9090/api/v1/alerts | 查看所有告警状态 |
amtool alert show | 查看Alertmanager中的告警 |
amtool silence list | 查看当前静音规则 |
kubectl exec -n monitoring prometheus-0 -- promtool tsdb analyze /data 01HKEJ... | 分析指定Block的序列分布 |
kubectl get prometheusrules -A | 查看所有PrometheusRule资源 |
rate()和irate()在数学定义上的区别是什么?为什么告警规则中应该用rate()而非irate()?在什么场景下irate()会给出完全错误的结论?| 核心知识点 | 掌握程度 | 验证方式 |
|---|---|---|
| 可观测性三支柱与Prometheus定位 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能解释三支柱协同关系和Pull模型优劣 |
| TSDB存储引擎与Gorilla压缩 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能解释Chunk编码原理和Block结构 |
| 高基数问题与容量规划 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能识别高基数标签并优化 |
| K8s Service Discovery配置 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能配置4种role的SD和relabel规则 |
| PromQL查询语言 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能编写聚合、分位数、子查询等高级查询 |
| Histogram分位数聚合 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能用histogram_quantile正确计算跨Pod P99 |
| Prometheus高可用与联邦 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能设计联邦架构和hashmod分片 |
| Thanos架构与部署 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能部署Thanos Sidecar+Store+Query+Compactor |
| Grafana Dashboard工程化 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能设计变量级联和Dashboard as Code |
| Alertmanager告警链路 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能配置路由、抑制、分组和分级通知 |
| Recording Rules分层优化 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能设计三层Recording Rules降低查询负载 |
| 告警风暴治理 | ☐ 了解 ☐ 理解 ☐ 掌握 | 能通过分组、抑制、聚合治理告警风暴 |