启用 stub_status 模块是获取 nginx 实时连接指标最直接、开销最低的方式,需三步:确认模块已编译(nginx -v | grep stub_status)、在 server 块内配置受控路径(如 /nginx-status)并限制访问、理解返回字段含义(active connections、accepts、handled、requests 及 reading/writing/waiting)。

启用 stub_status 模块是获取 Nginx 实时连接指标最直接、开销最低的方式。它不依赖外部工具,返回纯文本快照,适合快速诊断或集成监控。关键在于三步:确认模块存在、配置受控访问路径、读懂返回字段。
确认 stub_status 模块已编译进 Nginx
该模块不是默认开启的,但多数官方预编译包(如 Ubuntu 的 nginx-full、CentOS 的 nginx 主包)已内置。验证方法统一:
- 执行
nginx -V 2>&1 | grep -o with-http_stub_status_module - 有输出说明支持;无输出则需重新编译,添加
--with-http_stub_status_module参数 - 注意:若配置中出现
unknown directive "stub_status"错误,一定是模块未编译,配了也无效
在 server 块内配置 /nginx-status 路径
stub_status 只能在 location 上下文中启用,且必须嵌套在某个 server{...} 块中(不能放在 http 或全局 location 外层)。推荐做法:
- 单独建一个仅监听本地的 server,例如
listen 127.0.0.1:8080; - 添加 location,路径可自定义(如
/nginx-status),但避免用/status这类通用名 - 必须关闭访问日志:
access_log off;,否则每秒刷日志,影响 I/O - 必须设置 IP 访问控制:
allow指定可信来源(如本机、监控服务器),deny all放在最后
示例配置:
location /nginx-status {
stub_status on;
access_log off;
allow 127.0.0.1;
allow ::1;
deny all;
}
理解返回的三行指标含义
访问 http://127.0.0.1:8080/nginx-status 后,返回类似:
Active connections: 192 server accepts handled requests 124567 124567 876543 Reading: 3 Writing: 12 Waiting: 177
各字段作用明确:
- Active connections:当前全部 TCP 连接数(= Reading + Writing + Waiting)
- accepts:Nginx 启动以来接受的连接总数
-
handled:成功处理完的连接数;若
handled ,说明有连接异常中断(如超时、客户端断连) - requests:总 HTTP 请求次数;单位时间差值即为 QPS
- Waiting:keepalive 空闲连接数;长期占比高(>90%)说明复用好;若突降 + Writing 激增,可能后端开始响应变慢
-
Writing:正在发响应的连接;持续偏高且响应体大,需检查
output_buffers或后端延迟
用 curl 或脚本做简单采集
无需复杂平台,一条命令就能提取关键值。例如获取当前活跃连接数:
curl -s http://127.0.0.1:8080/nginx-status | head -1 | awk '{print $3}'
也可写入定时任务,每 10 秒抓一次,存入日志或推给 Prometheus 等系统。重点是让数据流动起来,而不是只看一眼。











