通过Nginx stub_status模块可实时获取连接状态,包括活跃连接数、accepts/handled/requests计数及Reading/Writing/Waiting细分状态,用于监控拥塞与异常。

通过 Nginx 自带的 stub_status 模块,可以快速获取当前服务的实时连接状态,包括活跃连接数、等待请求(accept queue)数量等关键指标,无需额外工具或侵入式改造。
启用 stub_status 模块并配置访问端点
Nginx 编译时默认已包含 ngx_http_stub_status_module,但需在 server 或 location 块中显式启用:
- 在配置文件中添加一个专用 location,例如:
location /nginx-status {<br> stub_status on;<br> access_log off;<br> allow 127.0.0.1;<br> deny all;<br>} - 必须限制访问来源(如仅允许本地或运维 IP),避免敏感连接信息暴露到公网
- 重启或重载 Nginx:`nginx -s reload`
理解 stub_status 返回字段含义
访问 /nginx-status(如 curl http://localhost/nginx-status)返回类似内容:
Active connections: 123<br>server accepts handled requests<br> 123456 123456 789012<br>Reading: 2 Writing: 10 Waiting: 111
- Active connections:当前所有 TCP 连接总数(含空闲、读取、写入、等待状态)
- accepts:Nginx 自启动以来接受的总连接数
-
handled:成功处理(未因资源不足被丢弃)的连接数;若
handled ,说明出现过 accept queue 溢出 - requests:总共处理的 HTTP 请求次数(通常 ≥ handled)
- Reading:正在读取请求头的连接数(轻量,一般个位数)
- Writing:正在向客户端发送响应的连接数
- Waiting:处于 keep-alive 空闲状态、等待新请求的连接数(即“空闲长连接”)
识别 accept queue 拥塞与连接异常
stub_status 本身不直接显示内核 accept queue 长度,但可通过间接方式发现排队问题:
- 持续观察
accepts ≠ handled:差值增大说明有连接在三次握手完成后、尚未被 Nginx accept() 调用取走,积压在内核 backlog 队列中 - 结合系统命令验证:
ss -lnt | grep :80查看 Recv-Q 列(即当前 accept queue 长度);若长期 > 0,说明应用层处理能力跟不上连接到达速度 - 常见诱因:worker_connections 设置过低、CPU/IO 瓶颈导致 accept() 调用延迟、突发流量冲击
集成到日常监控与告警
将 stub_status 数据接入 Prometheus、Zabbix 或脚本化采集:
- 用 curl + awk 提取数值,例如:
curl -s http://localhost/nginx-status | awk '/Active/ {print $3}'获取活跃连接数 - Prometheus 可使用 nginx-lua-prometheus(更丰富)或简单 exporter 将 stub_status 解析为指标
- 设置合理阈值告警:如 Active connections > 90% worker_connections,或 Waiting 持续高于 80% Active connections(可能预示请求处理延迟)











