$upstream_connect_time自Nginx 1.9.1起引入,需版本≥1.9.1且在log_format中显式配置才能记录TCP建连耗时(毫秒级),仅proxy_pass等upstream场景有效,非upstream请求显示“-”。

要在 Nginx 中记录并监控 $upstream_connect_time(即 Nginx 与后端服务器建立 TCP 连接的耗时),核心是两步:一是确保该变量可用,二是将其写入日志供采集分析。
确认 Nginx 版本支持该变量
$upstream_connect_time 自 Nginx 1.9.1 起正式引入,且仅在使用 proxy_pass、fastcgi_pass 等 upstream 指令时有值(非 upstream 场景为“-”)。请先运行 nginx -v 确认版本 ≥ 1.9.1。若低于此版本,需升级或改用 $upstream_header_time(含 connect + send + wait)做近似替代。
在 log_format 中定义含该变量的日志格式
在 http 块中添加自定义日志格式,例如:
log_format upstream_time '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$upstream_addr $upstream_status '
'$upstream_connect_time $upstream_header_time $upstream_response_time';
注意:
- $upstream_connect_time 单位为秒,精度为毫秒(如 0.002 表示 2ms);
- 若请求未进入 upstream(如 503 或 proxy_next_upstream 触发重试),该字段可能为空或显示“-”,建议配合 $upstream_status 一起看;
- 多个 upstream server 时,各时间字段以逗号分隔(如 10.0.1.1:80,10.0.1.2:80 对应 0.003,0.005)。
在 server 或 location 块中启用该日志格式
例如:
access_log /var/log/nginx/access.log upstream_time;
重启或重载 Nginx 生效:nginx -s reload。之后访问触发 upstream 请求,即可在日志中看到类似:
192.168.1.100 - - [10/Jul/2024:14:22:33 +0800] "GET /api/user HTTP/1.1" 200 124 "-" "curl/7.68.0" 10.0.2.5:8000 200 0.004 0.012 0.016
其中 0.004 即建连耗时 4ms。
对接监控系统(如 Prometheus + nginxlog-exporter)
原始日志需结构化解析才能用于监控:
- 使用 nginxlog-exporter,配置解析规则提取 upstream_connect_time 字段,暴露为 Prometheus 指标(如 nginx_upstream_connect_time_seconds);
- 在 Grafana 中绘制 P50/P90/P99 连接耗时趋势图;
- 设置告警:例如连续 5 分钟 P95 > 500ms,可能表示后端节点网络抖动或连接池不足。


















