Prometheus 3.x 常用 CLI 命令与工具详解

实测详解 Prometheus 3.15.0 的 promtool 命令(check config / query / tsdb)与 HTTP API(/api/v1/query、query_range、targets、rules、admin),并以 Pushgateway 作为抓取目标演示完整的"推送→抓取→查询"链路与自监控。所有输出均来自真实服务器实测

PrometheusPrometheus数据库2026/09/27

Prometheus 3.x 常用 CLI 命令与工具详解

目标:实测详解 Prometheus 3.15.0 的 promtool 命令(check config / query / tsdb)与 HTTP API(/api/v1/query、query_range、targets、rules、admin),并以 Pushgateway 作为抓取目标演示完整的"推送→抓取→查询"链路与自监控。所有输出均来自服务器 prom-server 与 Pushgateway 服务器真实实测(Prometheus 端口 9090;Pushgateway 服务器 prom-pushgateway-1,端口 9091)。

一、环境信息

信息项值
Prometheus 版本3.15.0(服务器 prom-server,端口 9090)
promtool 版本3.15.0(与服务端同版本)
Pushgatewaypushgateway 1.x(系统服务,监听 9091,主机名 prom-pushgateway-1)
网络prom-server 与 prom-pushgateway-1 处于同一内网,按主机名互相解析
数据目录/var/lib/prometheus
已开启参数--web.enable-lifecycle、--web.enable-otlp-receiver

二、前置条件

  • 已部署 Prometheus 3.x(部署与启动见《Prometheus 3.x 安装指南》《Prometheus 3.x Docker Compose 部署指南》)
  • 已安装 curl 用于 HTTP API 调用
  • 可选:部署 Pushgateway 作为抓取目标演示

三、部署步骤

3.1 部署 Pushgateway 作为抓取目标(演示)

Pushgateway 单独发布为独立二进制,下载后以 systemd 服务托管,监听端口 9091:

# 1. 创建运行用户
sudo useradd -r -s /usr/sbin/nologin pushgateway
# 2. 下载并解压 pushgateway 二进制(版本号以 GitHub releases 为准)
sudo wget -O /opt/pushgateway.tar.gz https://github.com/prometheus/pushgateway/releases/download/v1.10.0/pushgateway-1.10.0.linux-amd64.tar.gz
sudo tar -xzf /opt/pushgateway.tar.gz -C /opt
sudo mv /opt/pushgateway-1.10.0.linux-amd64/pushgateway /usr/local/bin/
# 3. 编写 systemd 服务单元
sudo tee /etc/systemd/system/pushgateway.service >/dev/null <<'EOF'
[Unit]
Description=Prometheus Pushgateway
After=network.target

[Service]
User=pushgateway
Group=pushgateway
ExecStart=/usr/local/bin/pushgateway --web.listen-address=:9091
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable pushgateway
sudo systemctl start pushgateway
# 4. 验证就绪
curl -s http://localhost:9091/-/healthy

实测输出:

OK

💡 命令解释:pushgateway 以系统服务监听 9091;prom-server 与它处于同一内网,后续 Prometheus 配置里用主机名 prom-pushgateway-1:9091 作为 targets 即可按主机名解析抓取。

💡 说明:/-/healthy 返回 OK 即 Pushgateway 就绪。向 Prometheus 的 conf/prometheus.yml 添加 job 后执行 curl -X POST http://localhost:9090/-/reload 热加载(实测返回 200)。

3.2 推送指标到 Pushgateway

echo 'my_batch_job_counter_total 100' | curl -s --data-binary @- http://localhost:9091/metrics/job/batch_job
# 连续递增推送(供 rate 演示)
for i in 1 2 3 4 5; do
  echo "my_batch_job_counter_total $((100+i*10))" | curl -s --data-binary @- http://localhost:9091/metrics/job/batch_job
  sleep 1
done

💡 命令解释:--data-binary @- 从标准输入读取 Prometheus text 格式指标;URL 路径 /metrics/job/<job名> 定义 job 标签;my_batch_job_counter_total 为 counter 类型(单调递增,适合 rate 演示)。

⚠️ 真实踩坑:向 Pushgateway 推送含中文指标名(如 温度计{房间="客厅"} 25.5)实测报错:

text format parsing error in line 1: invalid metric name

Pushgateway 1.x 的 text 解析仍要求 legacy ASCII 名称,UTF-8 指标名需走 Prometheus 的 OTLP 接收(见《Prometheus 3.x 配置参数详解》"常见问题"章节)。

3.3 promtool check config(配置校验)

promtool check config /etc/prometheus/prometheus.yml

实测输出:

Checking /etc/prometheus/prometheus.yml
  SUCCESS: 1 rule files found
 SUCCESS: /etc/prometheus/prometheus.yml is valid prometheus config file syntax

Checking /etc/prometheus/alerts.yml
  SUCCESS: 2 rules found

💡 命令解释:check config 校验主配置及其引用的规则文件语法,生产变更配置前必跑;1 rule files found/2 rules found 表示规则文件加载正常。

3.4 promtool query(HTTP API 查询 PromQL)

instant query(瞬时查询):

promtool query instant http://localhost:9090 'up'

实测输出:

up{instance="localhost:9090", job="prometheus"} => 1 @[1790459070.029]
up{instance="prom-pushgateway-1:9091", job="pushgateway"} => 1 @[1790459070.029]
up{instance="prometheus-apt-test:18080", job="utf8-test"} => 0 @[1790459070.029]

💡 命令解释:promtool query instant <server> <expr> 即时求值;输出格式 指标{标签} => 值 @[时间戳]。up=1 表示抓取成功(prometheus 自身与 pushgateway),up=0 为故意演示的失败目标(UTF-8 抓取失败,见"六、常见问题"的 6.3)。

range query(范围查询,rate/counter 演示):

promtool query range http://localhost:9090 'rate(my_batch_job_counter_total[2m])'

实测输出(节选):

{exported_job="batch_job", instance="prom-pushgateway-1:9091", job="pushgateway"} =>
0.643 @[1790459088.112]
0.6707777777777777 @[1790459089.112]
...
1.0318888888888889 @[1790459102.112]

💡 命令解释:promtool query range <server> <expr> 按步长返回一段时间的序列(matrix);rate(counter[2m]) 计算 counter 在 2 分钟窗口的每秒增长速率——Pushgateway 每次 push 后 counter 重置归零再增长,故速率呈递增(0.64→1.03/s)。

3.5 promtool tsdb 子命令(3.x 语法变化)

tsdb list(列出 TSDB 块):

promtool tsdb list /var/lib/prometheus

实测输出:

BLOCK ULID   MIN TIME     MAX TIME     DURATION     NUM SAMPLES  NUM CHUNKS   NUM SERIES   SIZE

💡 命令解释:tsdb list <db路径> 列出已压缩的 TSDB 块。实测输出无块——运行时间不足 2 小时(默认压缩阈值),数据仍在 head/WAL;强制压缩可稍后复查。

⚠️ 真实踩坑(3.x 与 2.x 差异):2.x 的 promtool tsdb ls / promtool tsdb snapshot / promtool tsdb check 在 3.15 实测均报:

promtool: error: expected command but got "ls", try --help

3.x 重命名为 tsdb list / tsdb dump / tsdb analyze,快照改走 admin API(见步骤 7)。

tsdb dump(导出样本):

promtool tsdb dump /var/lib/prometheus 2>/dev/null | head -3

实测输出:

{__name__="go_gc_cleanups_executed_cleanups_total", instance="localhost:9090", job="prometheus"} 0 1790458423096
{__name__="go_gc_cleanups_executed_cleanups_total", instance="localhost:9090", job="prometheus"} 0 1790458438096
{__name__="go_gc_cleanups_executed_cleanups_total", instance="localhost:9090", job="prometheus"} 0 1790458453096

💡 命令解释:tsdb dump 直接导出磁盘上的原始样本(指标+标签+值+毫秒时间戳),用于数据排查/迁移前检查。

3.6 HTTP API:/api/v1/query、query_range、targets、rules

query(瞬时查询,与 promtool instant 等价):

curl -s --get "http://localhost:9090/api/v1/query" --data-urlencode 'query=up'

实测输出:

{"status":"success","data":{"resultType":"vector","result":[{"metric":{"__name__":"up","instance":"localhost:9090","job":"prometheus"},"value":[1790458430.393,"1"]}]}}

query_range(范围查询):

curl -s --get "http://localhost:9090/api/v1/query_range" \
  --data-urlencode 'query=up' \
  --data-urlencode "start=$(($(date +%s)-300))" \
  --data-urlencode "end=$(date +%s)" \
  --data-urlencode 'step=60'

实测输出(关键字段):

resultType: matrix series数: 3
第一条前3点: [[1790458824, '1'], [1790458884, '1'], [1790458944, '1']]

💡 命令解释:start/end 为 Unix 时间戳,step 为采样步长(秒);返回 matrix(多条带时间戳序列)。

targets(抓取目标状态):

curl -s http://localhost:9090/api/v1/targets | python3 -c "import json,sys; [print(t['labels'].get('job'), t['scrapeUrl'], t['health']) for t in json.load(sys.stdin)['data']['activeTargets']]"

实测输出:

prometheus   http://localhost:9090/metrics         up
pushgateway  http://prom-pushgateway-1:9091/metrics up
utf8-test    http://prometheus-apt-test:18080/metrics down

💡 说明:/api/v1/targets 是排障第一站——down 的目标可同时取 lastError 字段看失败原因(UTF-8 目标实测 lastError 为 expected metric name after HELP, got "\xe6")。

rules(规则状态):

curl -s http://localhost:9090/api/v1/rules | python3 -c "import json,sys; g=json.load(sys.stdin)['data']['groups'][0]; print('group:', g['name'], [(r['type'], r.get('name') or r.get('alert')) for r in g['rules']])"

实测输出:

group: example-group | rules: [('recording', 'job:up:sum'), ('alerting', 'InstanceDown')]

💡 说明:返回当前加载的规则组;recording rule 可像普通指标一样查询(实测 query=job:up:sum 返回各 job 的 up 求和)。

3.7 admin API:TSDB 快照(3.x 替代 tsdb snapshot)

curl -s -X POST http://localhost:9090/api/v1/admin/tsdb/snapshot

未开启 --web.enable-admin-api 实测输出:

{"status":"error","errorType":"unavailable","error":"admin APIs disabled"}

⚠️ 说明:3.x 的 promtool tsdb snapshot 已移除,快照改走 admin API,但 --web.enable-admin-api 默认关闭(实测 403 级别报错)。开启后(apt 安装环境实测)返回:

{"status":"success","data":{"name":"20260926T213128Z-5e7a03741436bdd5"}}

快照目录位于数据目录 snapshots/<name>。

3.8 curl /metrics 自监控

curl -s http://localhost:9090/metrics | wc -l
curl -s "http://localhost:9090/api/v1/query?query=prometheus_tsdb_head_series"

实测输出:

1198
{"status":"success","data":{"resultType":"vector","result":[{"metric":{"__name__":"prometheus_tsdb_head_series"},"value":[1790459180.159,"115"]}]}}

💡 说明:/metrics 暴露 1198 行自监控指标(TSDB、抓取、Go 运行时等);prometheus_tsdb_head_series 为当前活跃序列数(115),可用 Grafana 对接告警。

四、配置说明

4.1 Pushgateway 抓取配置(conf/prometheus.yml 追加)

scrape_configs:
  - job_name: "pushgateway"
    static_configs:
      - targets: ["prom-pushgateway-1:9091"]

💡 说明:prom-pushgateway-1 与 prom-server 处于同一内网,Prometheus 按主机名直接解析抓取;修改配置后 curl -X POST http://localhost:9090/-/reload 热加载(实测 200)。

五、注意事项

  • promtool 必须与服务端同版本(实测均为 3.15.0),跨版本可能输出/行为不一致
  • 3.x 中 promtool tsdb ls/snapshot/check 已移除(实测报 expected command),快照用 admin API 且需 --web.enable-admin-api
  • Pushgateway 适合批处理任务短生命周期指标;长期运行的 exporter 应直接抓取,不要都走 pushgateway(避免单点与过期数据)
  • 指标名保持 ASCII 兼容命名,UTF-8 名称只走 OTLP(实测 text 抓取拒绝)
  • admin API 无鉴权,勿将 9090 暴露公网

六、常见问题

6.1 promtool query range 返回空

原因:目标尚无数据或 counter 无增长(rate 至少需窗口内有 2 个样本且递增)。实测初次 push 一次后 range 为空,连续递增 push 后即有数据。

解决:确认目标 up(promtool query instant ... 'up'),等待抓取周期,counter 持续递增再查 rate。

6.2 pushgateway 目标一直 unknown / down

原因:目标不在同一内网(主机名无法解析)或端口不通。

解决:确认推送端与抓取端处于同一内网;curl http://localhost:9091/-/healthy 验证;用 /api/v1/targets 的 lastError 定位。

6.3 抓取 UTF-8 指标名目标失败(down)

原因:实测 Prometheus 3.15 text/OpenMetrics 抓取报 expected metric name after HELP, got "\xe6" ("INVALID")——UTF-8 名称默认启用但抓取解析路径仍按 legacy 校验;Pushgateway 推送中文名同样报 invalid metric name。

解决:抓取目标用 ASCII 名称;UTF-8 指标走 OTLP:--web.enable-otlp-receiver + otlp.translation_strategy: NoUTF8EscapingWithSuffixes(见《Prometheus 3.x 配置参数详解》)。

6.4 /api/v1/admin/tsdb/snapshot 报 admin APIs disabled

原因:--web.enable-admin-api 默认关闭(实测)。

解决:启动参数加 --web.enable-admin-api(生产注意鉴权),快照目录在数据目录 snapshots/ 下。

七、参考链接


本文档由 www.quzuo.net 平台开发