stub_status模块不提供传统连接池监控,仅统计客户端到nginx的tcp连接状态,需通过active/reading/writing/waiting四指标分析瓶颈趋势;启用前须确认编译支持、正确配置server块内独立端口与路径,并注意多worker下数据非全局。

stub_status 模块本身不提供“连接池”监控——Nginx 没有传统意义的数据库或上游连接池(如 keepalive_connections 到后端),它监控的是 客户端到 Nginx 的 TCP 连接状态。所谓“连接池状态”,实际是指活跃连接的分布与压力特征,可通过 Active/Reading/Writing/Waiting 四项指标组合判断是否逼近瓶颈。预警的关键不是阈值绝对值,而是状态失衡趋势。
确认模块可用并安全暴露接口
模块未启用,后续所有监控都无效。执行以下命令验证:
- nginx -V 2>&1 | grep -o with-http_stub_status_module —— 有输出才表示已编译支持
- 若无输出,需重新编译 Nginx 并添加 --with-http_stub_status_module 参数
- 配置必须放在 server 块内,推荐用独立本地监听端口隔离,例如:
listen 127.0.0.1:8081;
location /_nxs {
stub_status;
access_log off;
allow 127.0.0.1;
deny all;
}
}
路径避开 /status 等通用名,防止被扫描;禁止日志写入,避免高频采集压垮磁盘。
读懂三行返回里隐藏的瓶颈信号
访问 http://127.0.0.1:8081/_nxs 返回固定格式纯文本,例如:
server accepts handled requests
156890 156890 423156
Reading: 1 Writing: 28 Waiting: 113
- Active connections:当前保持的全部 TCP 连接数(含空闲)
- Reading 长时间偏高(如 >5% Active)→ 客户端发包慢、网络延迟大,或存在慢速 HTTP 攻击
- Writing 持续高位(如 >30% Active 且波动小)→ 后端响应慢、网卡/带宽打满、或大文件传输阻塞
- Waiting 占比过低(如
- accepts ≠ handled:accepts 显著大于 handled → worker 接收连接但无法处理,常见于 worker_connections 不足或系统级资源(如 file descriptor)耗尽
用脚本实现轻量级预警采集
stub_status 不支持 JSON 或结构化输出,但字段位置稳定,适合用正则精准提取。以下为 Bash 示例(每 10 秒采集一次,写入 Prometheus 文本文件):
#!/bin/bashURL="http://127.0.0.1:8081/_nxs"
OUT="/var/lib/node_exporter/textfile/nginx.prom"
data=$(curl -s "$URL" 2>/dev/null)
if [ -n "$data" ]; then
active=$(echo "$data" | awk '/Active connections:/ {print $3}')
reading=$(echo "$data" | awk '/Reading:/ {print $2}')
writing=$(echo "$data" | awk '/Writing:/ {print $2}')
waiting=$(echo "$data" | awk '/Waiting:/ {print $2}')
echo "nginx_stub_active_connections $active" > "$OUT"
echo "nginx_stub_reading_connections $reading" >> "$OUT"
echo "nginx_stub_writing_connections $writing" >> "$OUT"
echo "nginx_stub_waiting_connections $waiting" >> "$OUT"
fi
配合 cron 或 systemd timer 执行该脚本,再由 node_exporter 的 textfile collector 暴露给 Prometheus。告警规则可设为:
- Writing > 50 且持续 3 分钟 → 触发“响应阻塞”告警
- Active > 90% worker_connections → 触发“连接水位过高”告警
- Waiting / Active 80% → 触发“连接复用异常”告警
注意多 worker 下的统计范围
stub_status 默认只统计 当前处理请求的那个 worker 进程 的数据。如果你有 4 个 worker,直接 curl 可能每次看到不同数值。要获取全局近似值,需满足两个条件之一:
- 确认 accept_mutex off; 已设置(默认 on),使连接更均匀分发
- 或改用 nginx-prometheus-exporter 这类工具,它会轮询所有 worker 的 stub_status 并自动聚合
单纯依赖单次 stub_status 返回值做容量评估,容易低估真实负载。











