17.1.3 采集层:Exporter与Pushgateway
采集层负责将各类系统与业务指标以统一的格式提供给 Prometheus。核心是 Exporter 拉取模式与 Pushgateway 推送模式协同:前者适用于可被主动抓取的服务与节点,后者用于短生命周期或无法暴露端点的任务。
原理草图:Exporter 与 Pushgateway 数据流#
Exporter 的角色与分类#
- 通用 Exporter:Node Exporter、Blackbox Exporter、SNMP Exporter。
- 中间件 Exporter:MySQL、Redis、Kafka、Nginx 等。
- 自定义 Exporter:SDK 或 textfile collector 输出业务指标。
Exporter 安装与采集示例(Node Exporter)#
1)安装并启动
# 下载并解压
cd /opt
wget https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-amd64.tar.gz
tar xf node_exporter-1.7.0.linux-amd64.tar.gz
ln -s /opt/node_exporter-1.7.0.linux-amd64 /opt/node_exporter
# 启动(前台验证)
/opt/node_exporter/node_exporter \
--web.listen-address=":9100" \
--collector.systemd \
--collector.textfile.directory="/var/lib/node_exporter/textfile"
2)验证指标端点
curl -s http://127.0.0.1:9100/metrics | head -n 5
预期:输出 node_ 前缀的指标,如 node_cpu_seconds_total。
3)Prometheus 抓取配置
# /etc/prometheus/prometheus.yml
scrape_configs:
- job_name: "node"
static_configs:
- targets: ["192.168.10.10:9100","192.168.10.11:9100"]
4)指标命名与标签示例
# HELP node_filesystem_size_bytes Filesystem size in bytes.
# TYPE node_filesystem_size_bytes gauge
node_filesystem_size_bytes{fstype="xfs",mountpoint="/"} 1.073741824e+11
说明:_bytes 为单位后缀,fstype/mountpoint 为低基数标签。
Pushgateway 适用场景与推送示例#
场景:批处理/CI 任务结束后上报一次性指标。
1)启动 Pushgateway
docker run -d --name pushgateway -p 9091:9091 prom/pushgateway:latest
2)推送任务指标
cat <<'EOF' > /tmp/job_metrics.txt
# TYPE job_duration_seconds gauge
job_duration_seconds 12.34
# TYPE job_success_total counter
job_success_total 1
EOF
# 推送到 Pushgateway,job 与 instance 为分组标签
curl --data-binary @/tmp/job_metrics.txt \
http://127.0.0.1:9091/metrics/job/backup/instance/host01
3)Prometheus 抓取 Pushgateway
# /etc/prometheus/prometheus.yml
scrape_configs:
- job_name: "pushgateway"
honor_labels: true
static_configs:
- targets: ["192.168.10.20:9091"]
4)清理历史指标(避免残留)
curl -X DELETE http://127.0.0.1:9091/metrics/job/backup/instance/host01
关键命令解释#
node_exporter --collector.textfile.directory:启用 textfile collector 读取自定义指标文件。curl --data-binary:以原样发送指标文本,避免换行丢失。honor_labels: true:保留 Pushgateway 的 job/instance 标签,避免被覆盖。
典型采集架构示例#
[主机] Node Exporter --> Prometheus
[中间件] Redis Exporter --> Prometheus
[业务] /metrics SDK --> Prometheus
[短作业] Task -> Pushgateway -> Prometheus
排错清单(常见问题与处理)#
-
Prometheus 抓不到指标
- 检查端口:ss -lntp | grep 9100
- 手工访问:curl http://目标IP:9100/metrics
- 防火墙放行:firewall-cmd --add-port=9100/tcp --permanent && firewall-cmd --reload -
指标为空或缺失
- Exporter 启动参数错误:检查启动日志
- 采集器被禁用:例如 Node Exporter 需显式开启某些 collector -
Pushgateway 历史指标残留
- 任务结束后执行 DELETE
- 增加 job 唯一标识避免覆盖错误
练习#
- 在两台机器部署 Node Exporter,并在 Prometheus 中完成抓取配置。验证
up{job="node"}为 1。 - 编写一个 5 秒执行的脚本,推送
job_duration_seconds到 Pushgateway,并在 Prometheus 中查询该指标。 - 通过 textfile collector 生成自定义指标
app_build_info{version="1.0.0"} 1并验证展示。