nginx stub_status模块非默认启用,需用nginx -v确认含with-http_stub_status_module;配置必须在location块中,配合access_log off和allow/deny;返回三行纯文本,含active connections、accepts/handled/requests及reading/writing/waiting状态。

要利用 stub_status 结合 Prometheus 实现 Nginx 静态连接实时状态监控,核心是让 Prometheus 能采集到 Nginx 暴露的连接指标(如活跃连接数、已接受/处理/请求总数),关键在于正确配置 Nginx 的 stub_status 模块,并通过 Prometheus 的 nginx_exporter 或直接抓取(需适配)完成指标转换与采集。
确保 Nginx 编译并启用 stub_status 模块
Nginx 默认通常已包含 http_stub_status_module,但需确认启用。可通过以下命令验证:
nginx -V 2>&1 | grep -o with-http_stub_status_module
若无输出,需重新编译 Nginx 并添加 --with-http_stub_status_module 参数。启用后,在 server 或 location 块中配置状态端点:
location /nginx_status {<br> stub_status on;<br> allow 127.0.0.1; # 仅允许本地或监控节点访问<br> deny all;<br>}重启 Nginx 后,访问 http://localhost/nginx_status 应返回类似:
Active connections: 3<br>server accepts handled requests<br> 12345 12345 67890<br>Reading: 0 Writing: 1 Waiting: 2
部署 nginx_exporter 作为指标翻译桥接
Prometheus 无法直接解析 stub_status 的纯文本输出,需借助 nginx_exporter 将其转换为 Prometheus 可识别的 metrics 格式。
- 下载对应平台的二进制文件,或使用 Docker:
docker run -d --name nginx-exporter -p 9113:9113 nginxinc/nginx-prometheus-exporter --nginx.status-url http://nginx-host:80/nginx_status - 若 Nginx 在宿主机且未暴露端口,可用
--nginx.status-url http://host.docker.internal:80/nginx_status(Docker Desktop)或宿主机 IP - 确保 exporter 能稳定访问
/nginx_status,超时或权限拒绝会导致nginx_up{job="nginx"} == 0
配置 Prometheus 抓取 nginx_exporter 指标
在 Prometheus 的 prometheus.yml 中添加 job:
scrape_configs:<br> - job_name: 'nginx'<br> static_configs:<br> - targets: ['localhost:9113']
重载配置:curl -X POST http://localhost:9090/-/reload(需启用 --web.enable-admin-api)。稍等片刻,在 Prometheus 表达式浏览器中输入 nginx_connections_active 即可看到实时活跃连接数时间序列。
常用指标包括:
-
nginx_connections_active:当前活跃连接数(对应 “Active connections”) -
nginx_connections_accepted_total:已接受连接总数 -
nginx_connections_handled_total:已处理连接总数 -
nginx_requests_total:总请求数(对应 “requests” 行) -
nginx_connections_reading、writing、waiting:分别对应 Reading/Writing/Waiting 状态连接数
构建基础告警与看板(可选但推荐)
基于采集到的指标,可快速落地实用监控:
- 告警规则示例(
alert.rules):groups:<br>- name: nginx-alerts<br> rules:<br> - alert: NginxHighActiveConnections<br> expr: nginx_connections_active > 1000<br> for: 2m<br> labels:<br> severity: warning<br> annotations:<br> summary: "Nginx active connections too high"
- Grafana 看板:导入 ID 为 10177 的官方 Nginx Exporter Dashboard,即可可视化连接趋势、请求速率、状态分布等
不复杂但容易忽略。










