如何用 Prometheus 监控 K8s Pod 的自定义指标?
让 Prometheus 采集 Pod 自定义指标的完整链路:应用暴露 /metrics → Pod 加 prometheus.io/scrape 注解 → Prometheus K8s 服务发现配置 relabel 规则 → 指标入库查询。附完整 YAML。
四步:应用在 /metrics 暴露指标 → Pod 打注解 prometheus.io/scrape: "true" → Prometheus 的 kubernetes_sd 配置用 relabel 只抓带注解的 Pod → 查询验证。
1. 应用暴露指标
用客户端库在 /metrics 暴露自定义指标(如 orders_created_total)。
2. Pod 加注解
metadata:
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/metrics"
3. Prometheus 服务发现配置
scrape_configs:
- job_name: 'kubernetes-pods'
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
action: replace
target_label: __metrics_path__
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
target_label: __address__
这段 relabel 的含义:只保留带 scrape 注解的 Pod,并按注解改写抓取路径与端口。
4. 验证
Prometheus UI 的 Targets 页应看到 Pod 被抓取;查询 orders_created_total 确认指标入库。
观测云对照
观测云 DataKit 以 DaemonSet 部署后自动发现容器内应用的指标端点,自定义业务指标经 OTLP 或 prom 采集器直传观测云;Pod 标签、命名空间等 K8s 元数据自动附加,无需手写 relabel 规则。
常见问题(FAQ)
Q:注解加了但 Targets 里看不到? 检查 Prometheus 的 RBAC(需要 pods get/list/watch 权限)与 relabel 正则是否匹配。
Q:自定义指标能和 HPA 联动吗? 需要装 prometheus-adapter 把指标暴露为 K8s custom metrics API。