需通过指标建模推断nginx upstream keepalive连接池复用率与空闲连接数:复用率看建连频次/请求总量比值、time_wait下降及handled/accepts趋近;空闲连接数通过5xx激增、connect_time飙升及worker连接占比逼近上限间接判断。

要通过 Grafana 展示 Nginx 长连接池(upstream keepalive 连接池)的复用率与空闲连接数,关键不是“直接看到数字”,而是用可观测性手段还原连接复用行为——因为 Nginx 原生不暴露连接池实时占用数,需结合指标、日志和间接信号建模推断。
复用率:用请求级指标反推连接复用效果
复用率没有现成字段,但可通过以下组合指标判断复用是否高效:
-
后端建连频率下降:在 Prometheus 中计算单位时间新建连接数。例如用 nginx-exporter 的
nginx_upstream_connections_created_total(需 exporter 支持)或自定义日志指标;若该值明显低于请求总量(nginx_http_requests_total),说明复用率高 -
TIME_WAIT 对比法:在 Grafana 中接入后端服务器的
netstat -s | grep "segments retransmited\|active connection openings"或ss -s输出(通过 node_exporter + textfile collector)。复用率提升后,time_wait数量应下降 40%–70% -
handled/accepts 比值趋势:在 stub_status 或 vts 模块中,若
handled ≈ accepts(差值长期 500),则复用受阻
空闲连接数:依赖 upstream keepalive 模块的隐式状态
Nginx 不提供 “当前空闲连接数” 的实时指标,但可通过两个可靠代理指标反映其水位:
-
upstream 状态码分布:用
nginx_upstream_response_code_count{code=~"502|503|504"}。若 502/503 突增,常因 keepalive 连接池耗尽(no live upstreams或upstream connection is busy),间接说明空闲连接长期为 0 -
upstream 连接等待延迟:采集
nginx_upstream_connect_time_seconds的 P95。若该值稳定在毫秒级(如 100ms 峰值,且伴随connect_time = "-"日志,则说明反复建连,空闲池已枯竭 -
worker 进程级连接池上限监控:在 Grafana 中叠加
nginx_worker_connections_limit(来自 vts 模块)与nginx_vts_server_connections_total{state="active"}。当活跃连接数接近 worker_connections,且 upstream 错误同步上升,说明 keepalive 连接池被挤占
Grafana 面板实用配置建议
避免堆砌无意义图表,聚焦三个可行动的视图:
-
上游连接健康看板:柱状图展示各 upstream 的
5xx rate(5min)+ 折线图叠加avg by (upstream)(rate(nginx_upstream_connect_time_seconds_sum[5m])),异常时两者同升 -
复用效能趋势图:双 Y 轴——左轴为
rate(nginx_http_requests_total[1m])(QPS),右轴为rate(nginx_upstream_connections_created_total[1m])(建连频次),比值越低,复用越强 -
空闲池压力热力图:用
nginx_upstream_requests_total按 upstream 分组,按分钟统计请求量;再叠加nginx_upstream_response_time_seconds_sum / nginx_upstream_response_time_seconds_count(平均响应时间)。若某 upstream 请求密集但响应时间突升,大概率是空闲连接不足,新请求被迫排队建连
必须启用的基础采集能力
以上指标都依赖底层数据出口,缺一不可:
- 启用
ngx_http_vhost_traffic_status_module(推荐)或官方nginx-prometheus-exporter,禁用仅靠 stub_status 的方案 - 在 Nginx access log 中启用
$upstream_connect_time和$upstream_header_time,并确保 exporter 正确解析 - 错误日志设为
error_log /var/log/nginx/error.log warn;,便于关联upstream connection is busy等关键事件











