nginx-prometheus-exporter是官方推荐的轻量级方案,通过解析access log或stub_status暴露prometheus指标;需配置exporter、prometheus抓取及grafana看板,并注意生产环境日志权限、多实例区分等细节。

直接用 nginx-prometheus-exporter 暴露指标,是当前最轻量、兼容性最好、官方推荐的方案。它不依赖 Nginx 重编译或模块安装,只需解析 access log 或 stub_status,就能输出标准 Prometheus 格式数据。
一、部署 nginx-prometheus-exporter
Exporter 是指标“翻译器”,把 Nginx 原始日志或状态页转成 Prometheus 能读的 /metrics。
- 下载对应架构的二进制(如 Linux amd64),解压后赋予执行权限
- 推荐使用 access log 模式:启动时指定日志路径,支持 status code、vhost、upstream 等多维标签
- 若用 stub_status,需先在 Nginx 配置中启用:location /nginx_status { stub_status on; allow 127.0.0.1; deny all; }
- 启动命令示例:
./nginx-prometheus-exporter --nginx.scrape-uri http://127.0.0.1:8080/nginx_status --web.listen-address :9113 - 验证:访问
http://localhost:9113/metrics,看到类似nginx_http_requests_total{status="200",vhost="example.com"} 1234即成功
二、配置 Prometheus 抓取指标
Prometheus 主动拉取 exporter 暴露的数据,关键在 prometheus.yml 中正确定义 job。
- 在
scrape_configs下添加 job:job_name: 'nginx' -
static_configs中 targets 写 exporter 地址,如['192.168.1.100:9113'](Docker 环境避免用 localhost) - 可加
relabel_configs打标,例如用__address__提取实例名,便于区分多台 Nginx - 重启 Prometheus 或发
SIGHUP重载配置,进入 Prometheus UI → Status → Targets,确认状态为 UP
三、Grafana 导入与定制看板
Grafana 不生成数据,只负责把 Prometheus 的指标画成图表。直接复用成熟模板省时高效。
- 推荐面板 ID:10587(Nginx Exporter Full)或 11725(适配 VTS 模块,但 exporter 方案也兼容)
- 导入方式:Grafana → + → Import → 输入 ID → 选择已配置的 Prometheus 数据源
- 核心指标建议保留:
rate(nginx_http_requests_total[5m])(QPS)、nginx_http_response_count_total(各状态码分布)、nginx_upstream_response_time_seconds(上游延迟直方图)、nginx_connections_active(活跃连接数) - 增强实用性:添加变量(如
$vhost、$status)支持下拉筛选;设置 5xx 错误率告警(rate(nginx_http_response_count_total{status=~"5.."}[5m]) / rate(nginx_http_response_count_total[5m]) > 0.01)
四、生产环境注意事项
上线前绕不开的几个实际细节:
- access log 模式更推荐:比 stub_status 多出 upstream、vhost、request length 等维度,且不依赖 Nginx 特定模块
- 确保 log_format 包含必要字段,例如:
log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $upstream_addr $upstream_response_time'; - Exporter 进程需有读取 access log 的权限;若日志轮转频繁,建议配合
logrotate的copytruncate或使用tail -F模式 - 多实例场景下,通过 relabel 或静态 target 别名区分
instance标签,避免指标混淆 - 告警规则建议放在
alert.rules文件中,Prometheus 配置里引用,并测试触发逻辑











