$upstream_connect_time 是 nginx 1.19.10+ 引入的变量,精确记录与 upstream 建立 tcp 连接耗时(毫秒级),用于定位跨机房延迟、后端队列满、防火墙干预及连接拒绝等网络瓶颈,需在 log_format 中显式配置方可采集。

$upstream_connect_time 是 Nginx 1.19.10+ 版本引入的关键变量,它精确记录Nginx 与 upstream 建立 TCP 连接所花费的时间(单位:秒,精度为毫秒)。相比笼统的 $request_time 或 $upstream_response_time,它能单独剥离出“建连阶段”的耗时,是定位跨机房、高延迟链路、防火墙策略、后端连接拒绝等网络层瓶颈最直接的指标。
为什么 $upstream_connect_time 比 proxy_connect_timeout 日志更有效
-
proxy_connect_timeout是超时阈值,只在失败时触发日志(如upstream timed out (110: Connection timed out) while connecting to upstream),无法反映“慢但未超时”的建连抖动; -
$upstream_connect_time在每次请求中都真实记录,无论成功或失败(失败时显示为-),可统计 P50/P95/P99 连接耗时分布,发现隐蔽的长尾问题。
如何启用并采集该变量
需同时满足两个条件:
- Nginx ≥ 1.19.10(确认方式:
nginx -v); - 在
log_format中显式添加$upstream_connect_time:
log_format upstream_detail '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '$upstream_connect_time $upstream_header_time $upstream_response_time $request_time ' '$upstream_addr "$http_user_agent"'; access_log /var/log/nginx/access.log upstream_detail;
⚠️ 注意:
$upstream_connect_time默认不记录,即使配置了也不会出现在日志中,除非你主动把它写进log_format。
用它快速识别四类典型建连瓶颈
跨地域/跨云网络延迟高
观察到$upstream_connect_time稳定在 80–200ms(如上海 Nginx → 深圳后端),远高于同机房后端连接队列满或 accept() 慢
$upstream_connect_time出现明显尖峰(如从 3ms 突增至 300ms+),且集中在某几台 upstream IP,而其他实例正常 → 后端服务器net.core.somaxconn不足或应用 accept 线程阻塞(如 PHP-FPM 子进程全忙、Swoole Worker 负载打满)。防火墙/NAT 设备干预导致 SYN 重传
$upstream_connect_time多数为0.003、0.007、0.015、0.031(呈 2^n 毫秒阶梯式增长),这是典型的 Linux 内核 SYN 重传行为(初始 1s→3s→7s…),说明中间设备丢包或策略拦截。后端主动拒绝连接(connection refused)但未及时反馈
日志中大量出现$upstream_connect_time "-"(短横线),同时error.log有connect() failed (111: Connection refused)→ 后端进程崩溃、端口未监听,或被安全组/iptables DROP,Nginx 等待 connect 系统调用返回失败,耗时即为proxy_connect_timeout值(如设为 3s,则日志里-对应实际卡住约 3 秒)。
实用分析命令示例
-
查看建连最慢的 10 次请求(排除
-):awk '$12 != "-" && $12 > 0 {print $12, $16}' /var/log/nginx/access.log | sort -k1nr | head -10 # 假设 $12 是 $upstream_connect_time,$16 是 $upstream_addr -
统计各 upstream 地址的平均建连时间:
awk '$12 != "-" {sum[$16] += $12; cnt[$16]++;} END {for (i in sum) print i, sum[i]/cnt[i]*1000 "ms"}' /var/log/nginx/access.log | sort -k2nr -
检查是否出现“阶梯式”建连时间(怀疑 SYN 重传):
awk '$12 != "-" && $12 > 0.001 {printf "%.3f\n", $12*1000}' /var/log/nginx/access.log | sort -n | uniq -c | tail -20
配合调优的三项关键动作
- 缩小
proxy_connect_timeout至 2–5 秒,避免慢建连拖垮连接池; - 后端开启
tcp_tw_reuse=1和net.ipv4.ip_local_port_range="1024 65535",缓解短连接风暴下的端口耗尽; - 若使用 keepalive 连接池,确保
upstream块中配置keepalive 32;,并location中启用proxy_http_version 1.1; proxy_set_header Connection '';,减少重复建连需求。
不复杂但容易忽略











