关键是要打通安全暴露→标准化转换→稳定采集→可视告警四环节:1.确认stub_status编译支持并限制IP访问;2.用exporter或shell脚本将纯文本转为Prometheus指标;3.配置Prometheus抓取及阈值告警;4.结合Waiting/Reading/Writing等状态分析业务瓶颈。

要让监控系统实时抓取 Nginx stub_status 的业务指标,关键不是“开了接口就行”,而是打通安全暴露 → 标准化转换 → 稳定采集 → 可视告警这四个环节。它本身只输出三行纯文本,必须经过适配才能被 Prometheus、Zabbix 或 Grafana 消费。
一、先确保 stub_status 接口安全可用
模块未启用或配置错位,后续全部失效。务必验证并限制访问:
- 执行 nginx -V 2>&1 | grep -o with-http_stub_status_module,有输出才说明已编译支持
- 在某个 server 块内(不能放在 http 外层)添加 location,例如:
location /_nxs {
stub_status on;
access_log off;
allow 127.0.0.1;
allow 10.10.20.50; # Prometheus 采集机 IP
deny all;
} - 重载生效:nginx -s reload,再用 curl http://127.0.0.1/_nxs 测试返回是否为三行文本
二、把纯文本转成监控系统能读的格式
Prometheus 不认 “Active connections: 42” 这种写法,必须变成 nginx_stub_active_connections 42 这样的指标行。推荐两种轻量方案:
-
用 nginx-prometheus-exporter(最省心):
下载二进制,运行:
./nginx-prometheus-exporter -nginx.scrape-uri http://127.0.0.1/_nxs
默认监听 :9113/metrics,Prometheus 直接抓取即可 -
用 shell + textfile(零新增进程):
写一个每 10 秒执行的脚本,curl 抓取后用 awk 提取字段,输出为:
nginx_stub_accepts 123456
nginx_stub_handled 123456
nginx_stub_requests 789012
nginx_stub_active_connections 42
nginx_stub_waiting 38
写入 /var/lib/node_exporter/textfile/nginx.prom,node_exporter 自动加载
三、在 Prometheus 中配置抓取与基础告警
修改 prometheus.yml,加入 job:
- 若用 exporter:
- job_name: 'nginx'
static_configs:
- targets: ['127.0.0.1:9113'] - 若用 textfile:
- job_name: 'node'
static_configs:
- targets: ['127.0.0.1:9100'](前提是 node_exporter 已启用 textfile 收集器) - 加一条简单告警规则(如活跃连接超阈值):
expr: nginx_stub_active_connections > 800
for: 2m
labels:
severity: warning
annotations:
summary: "Nginx active connections high"
四、识别真正有用的业务指标含义
别只盯着 Active connections。结合业务场景看这几项才有意义:
- Waiting / Active connections > 0.8:说明 keep-alive 复用充分,是健康信号;但若 Waiting 长期接近 100%,且 Writing 持续为 0,可能后端无响应或 upstream 超时太短
- accepts − handled 持续增大:内核 accept queue 积压,需查 ss -lnt | grep :80 的 Recv-Q 是否长期非零
- requests / handled 显著 > 1(比如 3.5):说明平均每个 TCP 连接处理了 3–4 个请求,keep-alive 利用率高;低于 1.2 可能客户端频繁建连或超时过短
- Reading 长时间 > 5:关注大文件上传、慢客户端或未完成的 POST 请求体











