架构与职责

  • Prometheus:抓取/存储时序指标(TSDB),支持 PromQL 查询与记录规则
  • Alertmanager:告警管理(分组、抑制、静默、路由)
  • Grafana:仪表盘与告警可视化
  • Exporter:Node/Kube/应用自定义指标

K8s 中通常选择 kube-prometheus-stack 一键部署,涵盖上述组件。

快速部署(Helm)

1
2
3
4
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm install kube-prom prometheus-community/kube-prometheus-stack \
-n monitoring --create-namespace

指标命名与标签规范

  • 名称:<component>_<metric>_<unit>(如 http_request_duration_seconds
  • 标签:{app="svc", env="prod", instance="10.0.0.1:8080"}
  • 直方图/摘要:Histogram 用于 P90/P99 延迟估算(通过 histogram_quantile),Summary 端侧计算不可聚合,建议优先使用 Histogram

自定义指标示例(Go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var (
reqDur = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "order",
Name: "request_duration_seconds",
Buckets: prometheus.DefBuckets,
},
[]string{"path", "method"},
)
)

func init() {
prometheus.MustRegister(reqDur)
}

func handler(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// ... 业务逻辑
reqDur.WithLabelValues(r.URL.Path, r.Method).
Observe(time.Since(start).Seconds())
}

在 HTTP 路由中暴露 /metrics 并接入 ServiceMonitor。

抓取与重标签(Relabel)

Prometheus 通过 ServiceMonitor/PodMonitor 发现目标,重标签用于规范标签与去噪。

1
2
3
4
5
6
7
8
9
scrape_configs:
- job_name: "nginx"
static_configs:
- targets: ["nginx:9113"]
relabel_configs:
- source_labels: [__address__]
regex: "(.*):.*"
target_label: "instance"
replacement: "$1"

记录规则与告警规则

记录规则(降低查询开销):

1
2
3
4
5
groups:
- name: latency
rules:
- record: job:http_request_duration_seconds:p99
expr: histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, job))

告警规则:

1
2
3
4
5
6
7
8
9
10
11
groups:
- name: k8s
rules:
- alert: HighErrorRate
expr: sum(rate(http_requests_total{status=~"5.."}[5m])) by (job) / sum(rate(http_requests_total[5m])) by (job) > 0.05
for: 10m
labels:
severity: critical
annotations:
summary: "High error rate on {{ $labels.job }}"
description: "5xx rate > 5% for 10m"

Grafana 仪表盘与告警

  • 推荐 Dashboards:Node Exporter Full、Kubernetes / USE Method / API Server
  • 统一变量:namespace, pod, instance
  • 业务看板:核心接口 QPS、P95、错误率、队列长度、依赖下游

Grafana 告警:对核心 SLO(如 99.9% 成功率、P95 延迟)设置多维告警,并通过联动值班系统(飞书/Slack)路由分级通知。

远程写与长周期存储

Prometheus TSDB 默认本地存储,保留周期受限。使用 Remote Write + Thanos/Mimir/Cortex:

  • 高可用与无限容量
  • 跨环境聚合查询
  • 成本优化(分层存储)

安全与多租户

  • 禁止公网暴露 /metrics 与 Prometheus/Grafana 面板
  • 基于反向代理或 OIDC 做 SSO 与 ACL
  • 租户隔离:Grafana 组织/文件夹划分,Prometheus 多实例或基于 label 的策略隔离

踩坑

  • 指标爆炸(高基数 label):限制如 user_id 等维度,聚合到上层
  • 直方图桶不合理导致 P99 失真:根据业务延迟分布自定义 buckets
  • 过度抓取:缩短 scrape_interval 会放大负载,结合业务特性设定

FAQ

  • 如何只抓取特定命名空间?使用 namespaceSelector 或 relabel 过滤
  • P95 与 P99 如何计算?直方图 + histogram_quantile,确保 buckets 合理
  • 迁移历史数据?Thanos Sidecar 从现有 Prometheus 中统一聚合

总结

以规范化指标体系为基础,配合记录规则与可视化大盘,形成从数据采集到告警响应的闭环。随着规模增长,逐步引入远程写与集中存储,实现高可用与成本可控。