直接用 nginx 自带 stub_status 接口可实现 qps 和活跃连接数监控,需正确暴露接口、稳定采集并基于差值与阈值告警;配置时应启用模块、限制访问 ip、关闭日志,并通过 curl + awk 提取指标,再结合 prometheus/zabbix/elastic stack 集成多维监控。

直接用 Nginx 自带的 stub_status 接口就能实现 QPS 和活跃连接数的基础监控,不需要额外代理或重写逻辑。关键在于正确暴露接口、稳定采集数据、再通过差值和阈值做告警判断。
启用并安全暴露 stub_status 接口
先确认模块已编译进 Nginx:
nginx -V 2>&1 | grep --with-http_stub_status_module若无输出,需重新编译并添加 --with-http_stub_status_module 参数。
在 server 块中配置专用路径(不推荐用 /stub_status 这类通用名):
- 使用带环境标识的路径,例如
/status-prod或/nginx-metrics - 限制访问 IP,只允许可信监控端(如 Prometheus 服务器、Zabbix Agent 所在网段)
- 关闭该路径的日志记录:
access_log off
示例配置:
location /status-prod {stub_status on;
allow 10.10.5.0/24;
deny all;
}
从接口提取核心指标
stub_status 返回纯文本,格式固定:
server accepts handled requests
123456 123456 789012
Reading: 2 Writing: 10 Waiting: 111
其中:
- Active connections:当前活跃连接总数,直接取第一行第3个字段
- requests:累计 HTTP 请求总数,取第三行第3个字段
可用 curl + awk 快速提取:
curl -s http://127.0.0.1/status-prod | awk 'NR==1 {print $3}' # 活跃连接数curl -s http://127.0.0.1/status-prod | awk 'NR==3 {print $3}' # 累计请求数
计算 QPS 并设置告警阈值
QPS 是速率指标,不能单次读取,必须定时采样后做差值:
- 建议采集间隔 ≤ 15 秒(高波动业务可设为 5 秒)
- QPS ≈ (t₂.requests − t₁.requests) ÷ (t₂ − t₁)
- 持续低于 1.2 的
requests / handled比值,说明 keep-alive 复用差,可能客户端异常断连 - 若
accepts ≠ handled且差值持续扩大,说明连接被丢弃,要查worker_connections或系统文件描述符限制
常见告警场景:
- Active connections > 1000 且持续 1 分钟 → 可能遭遇 CC 攻击或上游雪崩
- Writing 连接数突增 + Waiting 显著下降 → 后端响应慢或超时,响应体堆积
- Waiting 连接长期 > 80% Active connections → keep-alive 空闲连接过多,可能客户端复用不足或超时设置过长
集成到主流监控系统
不建议手写轮询脚本长期维护,优先对接成熟 exporter:
-
Prometheus:用
nginx-prometheus-exporter,自动抓取 stub_status 并暴露标准指标,如nginx_http_requests_total、nginx_http_connections_active -
Zabbix:通过自定义 key 调用 curl 提取数值,再配置触发器,例如:
last(/nginx-server/nginx.active.connections) > 1200 - Elastic Stack:用 Metricbeat 的 nginx 模块,10 秒级采集,配合 Kibana 设置异常检测规则
无论选哪种,记得给指标打上标签:env、role、ip、zone,方便多维下钻分析。











