Prometheus Pushgateway 完全指南:从部署到告警可视化
前言在 Prometheus 的标准架构中监控数据采用Pull拉取模式采集——Prometheus 服务器定期从目标服务的/metrics端点拉取数据。这种模式对于长期运行的服务如 Web 应用、数据库非常有效但面对定时任务、批处理脚本、CI/CD 流水线等短暂运行的任务时就完全无能为力了——任务运行完就退出了Prometheus 根本来不及“抓”数据。Pushgateway 正是为解决这一问题而生。本文将带你从零开始完成 Pushgateway 的安装部署、数据推送、告警配置和 Grafana 可视化的全流程。一、Pushgateway 简介1.1 什么是 PushgatewayPushgateway 是 Prometheus 官方提供的一个中间代理组件它允许短暂运行的作业将监控指标主动推送Push到一个中心化的网关中暂存然后 Prometheus 再按照常规方式从 Pushgateway拉取Pull这些数据。简单来说Pushgateway 就是 Prometheus 的“收件箱”——那些“来无影去无踪”的短期任务可以把监控数据先“寄”到这里Prometheus 再定期来“取件”。1.2 工作流程text┌─────────────┐ 推送数据 ┌──────────────────┐ 拉取数据 ┌─────────────┐ │ 短期任务 │ ─────────────▶ │ Pushgateway │ ─────────────▶ │ Prometheus │ │ (脚本/定时) │ (HTTP POST) │ (网关/缓存) │ (Pull) │ (9090) │ └─────────────┘ └──────────────────┘ └─────────────┘ │ ▼ ┌─────────────┐ │ Grafana │ │ (3000) │ └─────────────┘核心流程短期任务通过 HTTP POST 将指标数据推送到 Pushgateway路径/metrics/job/job_namePushgateway 暂存并缓存这些数据Prometheus 定时从 Pushgateway 拉取数据Prometheus 根据告警规则计算并触发告警Grafana 从 Prometheus 查询数据并展示1.3 适用场景场景说明定时任务/批处理作业每天凌晨执行的备份脚本、数据统计任务CI/CD 流水线构建、测试任务生命周期只有几分钟防火墙后的服务Prometheus 无法穿透防火墙直接拉取数据短时运行的服务运行完即退出的临时任务1.4 注意事项Pushgateway 并非银弹使用时需注意不会自动清理过期数据如果客户端停止推送Prometheus 会一直拉取到最后一次推送的旧数据单点故障风险如果通过单个 Pushgateway 监控多个实例它可能成为性能瓶颈和单故障点不适用于实时监控Pushgateway 更适合批处理作业的结果监控而非实时状态监控官方建议Pushgateway唯一合理的用例是捕获服务级批处理作业batch job的执行结果。二、Pushgateway 安装部署2.1 方式一二进制安装推荐生产环境步骤一下载 Pushgateway 二进制包从 Prometheus 官方 GitHub 下载最新稳定版本bash# 下载以 v1.11.2 为例 wget https://github.com/prometheus/pushgateway/releases/download/v1.11.2/pushgateway-1.11.2.linux-amd64.tar.gz # 解压 tar -xzf pushgateway-1.11.2.linux-amd64.tar.gz # 移动到系统路径 sudo mv pushgateway-1.11.2.linux-amd64/pushgateway /usr/local/bin/步骤二创建专用系统用户bash# 创建无登录权限的系统用户 sudo useradd --no-create-home --shell /bin/false pushgateway步骤三创建 Systemd 服务文件操作文件/etc/systemd/system/pushgateway.servicebashsudo tee /etc/systemd/system/pushgateway.service EOF [Unit] DescriptionPrometheus Pushgateway Wantsnetwork-online.target Afternetwork-online.target [Service] Userpushgateway Grouppushgateway Typesimple ExecStart/usr/local/bin/pushgateway \ --web.listen-address:9091 \ --web.enable-admin-api \ --log.levelinfo [Install] WantedBymulti-user.target EOF该文件的作用定义 Pushgateway 作为 Systemd 服务实现开机自启和进程守护。步骤四启动服务bash# 重新加载 systemd 配置 sudo systemctl daemon-reload # 启动 Pushgateway sudo systemctl start pushgateway # 设置开机自启 sudo systemctl enable pushgateway # 查看运行状态 sudo systemctl status pushgateway步骤五验证服务bash# 检查进程 ps aux | grep pushgateway # 访问指标端点 curl http://localhost:9091/metricsPushgateway 默认监听9091 端口。如果能看到 Prometheus 格式的指标输出说明部署成功步骤六配置防火墙bash# CentOS 7 sudo firewall-cmd --permanent --add-port9091/tcp sudo firewall-cmd --reload # Ubuntu sudo ufw allow 9091/tcp2.2 方式二Docker 安装推荐测试/开发环境Docker 方式是最快捷的部署方式bash# 拉取镜像 docker pull prom/pushgateway # 运行容器 docker run -d \ --name pushgateway \ -p 9091:9091 \ --restartalways \ prom/pushgateway使用 Docker Compose 部署推荐操作文件docker-compose.ymlyamlversion: 3 services: pushgateway: image: prom/pushgateway:latest container_name: pushgateway restart: always ports: - 9091:9091 command: - --web.listen-address:9091 - --web.enable-admin-api 启动 bash docker-compose up -d三、配置 Prometheus 抓取 PushgatewayPushgateway 部署完成后需要配置 Prometheus 定期从 Pushgateway 拉取数据。操作文件/etc/prometheus/prometheus.yml在scrape_configs部分添加以下配置yamlscrape_configs: # ... 其他 job 配置 ... - job_name: pushgateway # 【重要】保留推送时携带的 job 和 instance 标签 honor_labels: true static_configs: - targets: [localhost:9091]配置项说明参数说明honor_labels: true至关重要确保 Prometheus 保留从 Pushgateway 推送过来的原始标签而不是用抓取目标的标签覆盖targetsPushgateway 的地址和端口使配置生效bash# 检查配置文件语法 promtool check config /etc/prometheus/prometheus.yml # 重新加载配置热加载不中断服务 sudo systemctl reload prometheus # 或重启服务 sudo systemctl restart prometheus验证在浏览器中访问http://Prometheus_IP:9090/targets查看pushgateway任务状态是否为UP。四、向 Pushgateway 推送监控数据4.1 使用 curl 推送数据Pushgateway 提供了标准的 HTTP API推送地址格式为texthttp://pushgateway_ip:9091/metrics/job/job_name/label1/value1/...1推送单个指标最简单的示例bashecho my_custom_metric 42.5 | curl --data-binary - http://localhost:9091/metrics/job/my_job2推送带标签的指标bashcat EOF | curl --data-binary - http://localhost:9091/metrics/job/my_job/instance/server1 # TYPE my_job_duration_seconds gauge # HELP my_job_duration_seconds Duration of my batch job in seconds my_job_duration_seconds{environmentproduction} 42.5 EOF3推送多个指标分组推送bashcat EOF | curl --data-binary - http://localhost:9091/metrics/job/backup_job/db/mysql # TYPE backup_success gauge backup_success 1 # TYPE backup_duration_seconds gauge backup_duration_seconds 120.5 # TYPE backup_size_bytes gauge backup_size_bytes 1073741824 EOFURL 路径说明job/backup_job作业名称必填db/mysql额外的标签键值对用于分组可选4.2 使用 Python 推送数据步骤一安装 Python 客户端库bashpip install prometheus_client步骤二编写 Python 推送脚本操作文件/opt/scripts/push_metrics.pypython#!/usr/bin/env python3 # -*- coding: utf-8 -*- from prometheus_client import Gauge, CollectorRegistry, push_to_gateway import time import random # 创建独立的注册表避免与默认注册表冲突 registry CollectorRegistry() # 定义指标Gauge 类型可增可减 backup_success Gauge(backup_success, Backup job success status (1success, 0fail), registryregistry) backup_duration Gauge(backup_duration_seconds, Backup job duration in seconds, registryregistry) backup_size Gauge(backup_size_bytes, Backup file size in bytes, registryregistry) # 模拟采集数据 success 1 # 假设备份成功 duration random.uniform(60, 180) # 模拟耗时 60-180 秒 size random.randint(100000000, 500000000) # 模拟文件大小 # 设置指标值 backup_success.set(success) backup_duration.set(duration) backup_size.set(size) # 推送到 Pushgateway # 分组键jobbackup_job, instanceserver1, envproduction push_to_gateway( localhost:9091, jobbackup_job, registryregistry, grouping_key{instance: server1, env: production} ) print(fMetrics pushed: success{success}, duration{duration:.2f}s, size{size} bytes)该文件的作用定义监控指标、采集数据并通过prometheus_client库推送到 Pushgateway。步骤三运行脚本bashpython3 /opt/scripts/push_metrics.py验证推送结果bashcurl http://localhost:9091/metrics | grep backup你应该能看到类似以下的输出textbackup_success{envproduction,instanceserver1,jobbackup_job} 1.0 backup_duration_seconds{envproduction,instanceserver1,jobbackup_job} 120.5 backup_size_bytes{envproduction,instanceserver1,jobbackup_job} 1073741824.0五、实战案例监控目录下的文件数量这是一个非常典型的 Pushgateway 使用场景——定时统计某个目录下的文件数量并上报。5.1 Shell 脚本实现操作文件/opt/scripts/file_count.shbash#!/bin/bash # 要监控的目录 MONITOR_DIR/var/log/myapp PUSHGATEWAY_URLhttp://localhost:9091/metrics/job/file_monitor/instance/server1 # 统计文件数量排除隐藏文件 FILE_COUNT$(find $MONITOR_DIR -type f 2/dev/null | wc -l) # 统计子目录数量 DIR_COUNT$(find $MONITOR_DIR -type d 2/dev/null | wc -l) # 推送到 Pushgateway cat EOF | curl --data-binary - $PUSHGATEWAY_URL # TYPE file_count gauge # HELP file_count Number of files in monitored directory file_count{dir$MONITOR_DIR} $FILE_COUNT # TYPE dir_count gauge # HELP dir_count Number of subdirectories in monitored directory dir_count{dir$MONITOR_DIR} $DIR_COUNT EOF echo $(date): file_count$FILE_COUNT, dir_count$DIR_COUNT /var/log/file_monitor.log该文件的作用统计指定目录下的文件和子目录数量并通过 curl 推送到 Pushgateway。赋予执行权限bashchmod x /opt/scripts/file_count.sh5.2 Python 脚本实现操作文件/opt/scripts/file_count.pypython#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import glob from prometheus_client import Gauge, CollectorRegistry, push_to_gateway # 要监控的目录 MONITOR_DIR /var/log/myapp # 创建注册表 registry CollectorRegistry() # 定义指标 file_count Gauge(file_count, Number of files in directory, [directory], registryregistry) dir_count Gauge(dir_count, Number of subdirectories, [directory], registryregistry) # 统计文件数量 try: files [f for f in os.listdir(MONITOR_DIR) if os.path.isfile(os.path.join(MONITOR_DIR, f))] dirs [d for d in os.listdir(MONITOR_DIR) if os.path.isdir(os.path.join(MONITOR_DIR, d))] file_count.labels(directoryMONITOR_DIR).set(len(files)) dir_count.labels(directoryMONITOR_DIR).set(len(dirs)) # 推送到 Pushgateway push_to_gateway( localhost:9091, jobfile_monitor, registryregistry, grouping_key{instance: server1} ) print(fPushed: files{len(files)}, dirs{len(dirs)}) except Exception as e: print(fError: {e})该文件的作用与 Shell 脚本功能相同使用 Python 实现目录文件数量统计和推送。5.3 配置定时任务Cron定时执行脚本实现周期性监控数据上报。操作文件/etc/crontab或使用crontab -ebash# 编辑当前用户的 crontab crontab -e # 添加以下行每5分钟执行一次 */5 * * * * /opt/scripts/file_count.sh # 或使用 Python 脚本 */5 * * * * /usr/bin/python3 /opt/scripts/file_count.pyCron 表达式说明*/5 * * * *表示每 5 分钟执行一次。验证定时任务bash# 查看当前用户的定时任务 crontab -l # 查看 cron 日志 tail -f /var/log/cron六、配置告警规则数据推送并采集后可以配置告警规则在指标异常时触发告警。6.1 创建告警规则文件操作文件/etc/prometheus/alerts.ymlyamlgroups: - name: pushgateway_alerts interval: 30s rules: # 告警1备份任务失败 - alert: BackupJobFailed expr: backup_success 0 for: 5m labels: severity: critical annotations: summary: 备份任务失败 description: 备份任务 {{ $labels.job }} 在实例 {{ $labels.instance }} 上执行失败请立即检查 # 告警2备份任务超过 5 分钟未推送数据任务可能未执行 - alert: BackupJobMissing expr: absent(backup_success) for: 10m labels: severity: warning annotations: summary: 备份任务未上报数据 description: 备份任务 {{ $labels.job }} 已超过 10 分钟未推送数据请检查任务是否正常运行。 # 告警3文件数量异常超过阈值 - alert: TooManyFiles expr: file_count 10000 for: 5m labels: severity: warning annotations: summary: 目录文件数量过多 description: 目录 {{ $labels.directory }} 下的文件数量为 {{ $value }}超过 10000 的阈值请及时清理。 # 告警4备份文件大小异常 - alert: BackupSizeAbnormal expr: backup_size_bytes 1000000 for: 5m labels: severity: warning annotations: summary: 备份文件大小异常 description: 备份文件大小仅为 {{ $value }} 字节远小于正常值请检查备份是否完整。该文件的作用定义 Prometheus 告警规则当指标满足特定条件时触发告警。6.2 在 Prometheus 中加载告警规则操作文件/etc/prometheus/prometheus.yml在rule_files部分添加告警规则文件yamlrule_files: - alerts.yml使配置生效bash# 检查配置promtool check config /etc/prometheus/prometheus.yml# 重新加载sudo systemctl reload prometheus验证告警规则在浏览器中访问http://Prometheus_IP:9090/alerts查看告警规则是否已加载。七、Grafana 添加图形展示7.1 配置 Prometheus 数据源步骤一访问 Grafana默认http://服务器IP:3000登录默认 admin/admin。步骤二左侧菜单 →Connections→Data Sources→Add data source→ 选择Prometheus。步骤三在HTTP区域URL 填写http://localhost:9090或 Prometheus 实际地址。步骤四点击Save Test显示绿色成功提示即可。7.2 手动创建 Dashboard方式一手动创建面板左侧菜单 →Dashboards→New→New Dashboard→Add visualization选择 Prometheus 数据源在查询编辑器中输入 PromQL文件数量趋势图promqlfile_count{directory/var/log/myapp}备份任务成功率promqlavg(backup_success) by (instance)备份任务耗时promqlbackup_duration_seconds{jobbackup_job}方式二导入现成 DashboardGrafana 官网有一些 Pushgateway 相关的 Dashboard 模板可供参考。在 Import 页面输入相关 Dashboard ID 即可导入。7.3 推荐的面板配置面板类型指标用途Statfile_count显示当前文件总数Time seriesfile_count展示文件数量变化趋势Statbackup_success显示最近一次备份状态1成功0失败Time seriesbackup_duration_seconds展示备份耗时趋势Table{jobbackup_job}展示所有备份相关指标详情八、Pushgateway 数据管理8.1 查看已推送的数据bash# 查看所有指标curl http://localhost:9091/metrics# 查看特定 job 的指标curl http://localhost:9091/metrics/job/backup_job8.2 删除指定分组的数据bash# 删除某个 job 的所有数据 curl -X DELETE http://localhost:9091/metrics/job/backup_job # 删除带分组键的数据 curl -X DELETE http://localhost:9091/metrics/job/backup_job/instance/server1重要提醒Pushgateway不会自动清理过期数据。如果客户端停止推送Prometheus 会一直拉取到旧数据可能导致误告警。建议在脚本中定期清理或使用--web.enable-admin-api配合定时清理任务。九、总结本文完整介绍了 Prometheus Pushgateway 从部署到使用的全流程涉及的核心文件和路径汇总如下阶段操作文件作用安装/etc/systemd/system/pushgateway.serviceSystemd 服务文件管理 Pushgateway 进程安装/usr/local/bin/pushgatewayPushgateway 二进制可执行文件Prometheus 配置/etc/prometheus/prometheus.yml添加pushgateway抓取任务数据推送/opt/scripts/push_metrics.pyPython 推送脚本数据推送/opt/scripts/file_count.shShell 脚本统计目录文件数并推送数据推送/opt/scripts/file_count.pyPython 脚本统计目录文件数并推送定时任务/etc/crontab或crontab -e定时执行推送脚本告警规则/etc/prometheus/alerts.yml定义告警规则GrafanaWeb UI 配置数据源配置和 Dashboard 创建核心要点回顾Pushgateway 解决什么问题让短暂运行的批处理作业也能被 Prometheus 监控安装方式二进制生产推荐和 Docker快速体验关键配置Prometheus 中honor_labels: true必须设置数据推送支持 curl 和 Prometheus Client SDK 两种方式告警配置重点关注absent()检测任务是否正常运行数据清理Pushgateway 不会自动清理过期数据需手动管理一句话总结Pushgateway 是 Prometheus 监控体系中不可或缺的“收件箱”组件让所有短暂运行的批处理任务都能被有效监控配合告警和 Grafana 可视化实现对非长期运行服务的完整监控闭环。