要让Prometheus有效监控Nginx,关键在于确保指标来源可靠、采集路径正确、数据维度可用;需启用nginx_stub_status模块并配置/ngx_status路径,部署nginx-prometheus-exporter指向该接口,再在Prometheus中配置scrape job采集指标,并关注活跃连接数、5xx错误率等核心指标。

要让 Prometheus 有效监控 Nginx 的核心性能数据,关键不是“把Exporter装上就行”,而是确保指标来源可靠、采集路径正确、数据维度可用。最常用且轻量的组合是 nginx_stub_status 模块 + nginx-prometheus-exporter,它能稳定提供连接数、请求速率、处理状态等基础但关键的运行时指标。
确认并启用 stub_status 模块
Nginx Exporter 依赖这个内置模块暴露原始指标,必须显式启用:
- 执行
nginx -V 2>&1 | grep -o with-http_stub_status_module,确认输出存在;若无,需重新编译 Nginx 并加入--with-http_stub_status_module - 在 server 或 http 块中添加 location 配置:
location /nginx_status { stub_status on; allow 127.0.0.1; deny all; } - 路径必须为
/nginx_status(Exporter 默认抓取此地址),且仅允许本地或监控节点访问 - 执行
nginx -t验证后nginx -s reload生效,再访问http://localhost/nginx_status确认返回类似Active connections: 5的文本
部署并验证 nginx-exporter
Exporter 是个独立二进制程序,不侵入 Nginx,只需正确指向 status 接口:
- 从 GitHub Release 下载对应平台的最新版(推荐 v0.12.0+,支持 worker 级指标)
- 启动命令示例:
./nginx-prometheus-exporter -nginx.scrape-uri http://127.0.0.1/nginx_status - 默认监听
:9113/metrics,访问该地址应看到以nginx_connections_active、nginx_http_requests_total等开头的指标行 - 若 Nginx 启用了 basic auth,加参数
-nginx.username user -nginx.password pass;HTTPS 场景加-nginx.ssl-verify=false - 建议用 systemd 或容器方式长期运行,并配置健康检查端点(如
/healthz)
在 Prometheus 中完成采集配置
Exporter 只是“翻译器”,真正存储和分析靠 Prometheus:
- 修改
prometheus.yml,在scrape_configs下新增 job:job_name: 'nginx' static_configs: - targets: ['nginx-exporter-host:9113']
- 可添加 relabel 规则打标,例如用
instance: nginx-prod区分不同实例 - 重启 Prometheus,进入 Web UI 的 Status → Targets 页面,确认该 job 状态为 UP
- 在 Graph 页面输入
nginx_http_requests_total或nginx_connections_active,观察是否返回时间序列数据,数值随真实请求波动
关注核心指标与初步告警方向
有了数据,下一步是聚焦真正影响服务稳定性的指标:
-
nginx_connections_active:活跃连接数,突增可能预示攻击或后端阻塞 -
nginx_http_requests_total{code=~"5.."} / rate(nginx_http_requests_total[5m]):5xx 错误率,超过 1% 可设为告警阈值 -
rate(nginx_http_requests_total[1m]):每秒请求数,结合历史基线判断异常飙升或骤降 - 若使用 v0.12.0+ 版本且 Nginx 配置了 VTS 或 status JSON 接口,还能获取
nginx_worker_connections_active{pid="12345"}这类带进程标签的指标,用于定位单个 worker 异常



















