ngx_http_stub_status_module是nginx内置轻量级状态模块,提供active connections及accepts/handled/requests等实时统计,需通过两次采样requests差值除以时间间隔估算qps,并推荐结合prometheus等工具实现持续监控与告警。

ngx_http_stub_status_module 是 Nginx 内置的轻量级状态模块,可实时暴露基本连接与请求统计信息,是估算当前 QPS(Queries Per Second)最直接、低开销的方式之一。它不记录历史或详细日志,但能提供秒级活跃指标,适合快速观测和简单监控集成。
启用 stub_status 并暴露接口
该模块默认编译进大多数官方 Nginx 发行版(可通过 nginx -V 2>&1 | grep -o with-http-stub-status-module 确认)。只需在 server 块中添加 location 配置并限制访问权限:
- 在配置中加入:
location /nginx-status {
stub_status;
allow 127.0.0.1;
allow 10.0.0.0/8;
deny all;
} - 重载 Nginx:nginx -s reload
- 访问 curl http://localhost/nginx-status,返回类似:
Active connections: 12
server accepts handled requests
123456 123456 789012
Reading: 0 Writing: 3 Waiting: 9
从响应中提取 QPS 近似值
stub_status 不直接输出 QPS,需结合三数字行(accepts / handled / requests)与时间窗口推算。关键逻辑如下:
- requests 是 Nginx 启动以来总处理请求数;
- 两次采样间隔 Δt 秒内,QPS ≈ (requests₂ − requests₁) / Δt;
- 推荐使用 1–5 秒间隔(如用 watch -n 1 'curl -s http://localhost/nginx-status | awk "NR==3 {print \$3}"' 实时观察 requests 变化);
- 注意:若 handled ≠ accepts,说明有连接被丢弃(如达到 worker_connections 上限),此时 QPS 可能失真,需同步检查 error.log 中的 “accept() failed” 记录。
结合 Prometheus 或脚本做持续采集
手动 curl 效率低且难留存,建议自动化采集:
- 用 curl + awk + bc 写简易脚本每秒计算差值并打印;
- 更推荐部署 nginx-prometheus-exporter,它会主动抓取 stub_status 并暴露为 Prometheus 格式指标(如 nginx_http_requests_total),再通过 rate(nginx_http_requests_total[1m]) 直接获得平滑 QPS;
- 若仅需告警,可用 Telegraf 的 nginx 插件或自定义 exec 输入,将 requests 值写入 InfluxDB,设置阈值触发通知。
注意事项与常见误区
stub_status 提供的是“全局平均”,不能反映后端真实负载或单请求耗时,使用时需明确其边界:
- 它统计的是进入 Nginx 的请求,包括 4xx/5xx、静态文件、健康检查等,非业务有效 QPS;如需过滤,应在 upstream 或应用层打标,stub_status 本身无过滤能力;
- 所有 worker 进程共享统计值,无法定位某 worker 是否过载;
- 若启用了 keepalive,Waiting 连接数高是正常现象,不代表压力大,真正关注点是 Active connections 和 requests 增速是否突增;
- 不要将 stub_status 开放到公网——它不鉴权,仅靠 IP 白名单,且暴露了服务运行时长等信息。











