本页目录

Prometheus 操作手册

Prometheus 是时序数据库 + 监控告警引擎。核心概念: target (采集目标), metric (指标), label (维度), rule (记录规则 + 告警规则), TSDB (时序存储)。

Target

# API 查询 target 状态
curl -s http://localhost:9090/api/v1/targets | jq '.data.activeTargets[] | {labels, health, lastError}'
# health: "up" = 正常, "down" = 采集失败
# lastError: 上次失败原因 (超时/拒绝连接/格式错误)

# 查哪些 instance 的 up 指标为 0 (不可达)
curl -s 'http://localhost:9090/api/v1/query?query=up==0' | jq '.data.result[] | .metric.instance'

# Web UI: http://localhost:9090/targets
# → 可看到每个 target 的 labels, last scrape time, scrape duration, errors

配置与热重载

# 检查配置语法
promtool check config /etc/prometheus/prometheus.yml
promtool check rules /etc/prometheus/rules/*.yml

# 热重载 (不重启, 不丢数据, 仅重新加载 rules + targets)
kill -HUP $(pidof prometheus)
# 或: curl -X POST http://localhost:9090/-/reload

典型 prometheus.yml 结构:

global:
  scrape_interval: 15s
  evaluation_interval: 15s

rule_files:
  - /etc/prometheus/rules/*.yml

scrape_configs:
  - job_name: node
    static_configs:
      - targets: ['localhost:9100', '192.168.1.7:9100']
        labels: { env: 'prod' }

TSDB 管理

# 数据目录 (每 2h 产生一个 block 目录)
du -sh /var/lib/prometheus/data
ls /var/lib/prometheus/data/           # 看到 01xxxx-02xxxx 的 block 目录

# TSDB 状态 (series 数、内存使用、block 数)
curl -s http://localhost:9090/api/v1/status/tsdb | jq '.data'
# headStats.numSeries: 当前活跃 series 数 (> 1M 需关注)
# headStats.chunkCount: 内存中的 chunk 数

# 删除旧数据 (需要 --web.enable-admin-api 启动参数, 默认不开)
curl -X POST -g 'http://localhost:9090/api/v1/admin/tsdb/delete_series?match[]={job="old-job"}'
# 标记删除后需 clean_tombstones
curl -X POST http://localhost:9090/api/v1/admin/tsdb/clean_tombstones

# 快照 (完整数据备份)
curl -X POST http://localhost:9090/api/v1/admin/tsdb/snapshot
# → /var/lib/prometheus/data/snapshots/<timestamp>/
# 快照可复制到另一台 Prometheus 直接使用

查询调试

# 即时查询
curl -s 'http://localhost:9090/api/v1/query?query=rate(node_cpu_seconds_total[5m])' | jq

# 范围查询 (step=采样间隔)
curl -s 'http://localhost:9090/api/v1/query_range?query=up&start=...&end=...&step=60s' | jq

# 列出所有 label values
curl -s http://localhost:9090/api/v1/label/__name__/values | jq '.data[:20]'
curl -s http://localhost:9090/api/v1/label/job/values | jq

故障排查

# Target down
curl http://<target>:<port>/metrics              # 检测 exporter 是否暴露数据
# → timeout → 防火墙/systemd/端口绑定问题
# → 200 但空 → exporter 在跑但没数据

# 内存占用大
# → 高基数 label (如 request_id, user_id) 为每个唯一值创建新 series
# → 检查: curl http://localhost:9090/api/v1/status/tsdb | jq '.data.headStats.numSeries'
# → 超过 100 万 → 考虑减少 label 维度或改 recording rules 预聚合

# 查询慢/超时
# → 检查 query 的范围和 step: 范围越大 step 越小 → 数据点越多
# → 改用 recording rules 预计算常用查询