如何用 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 确认指标入库。
若这些 Pod 指标也要进入观测云,可在 DataKit 的 prom 采集配置中接入已验证的指标端点。先用一个带固定标签的测试指标核对抓取结果,再确认命名空间、服务标签和采集范围;自动发现需要相应配置,不能仅凭 DaemonSet 运行就判断所有业务指标已接入。
常见问题(FAQ)
Q:注解加了但 Targets 里看不到? 检查 Prometheus 的 RBAC(需要 pods get/list/watch 权限)与 relabel 正则是否匹配。
Q:自定义指标能和 HPA 联动吗? 需要装 prometheus-adapter 把指标暴露为 K8s custom metrics API。