定位 Nginx 慢请求,通常可以从 请求链路分层排查:客户端 → Nginx → 后端(如 PHP/Java/Node) → 数据库/外部服务。下面按实战步骤说明。
在 nginx.conf 的 http 或 server 中:
log_format detailed '$remote_addr - $remote_user [$time_local] '
'"$request" $status '
'$body_bytes_sent '
'rt=$request_time uct=$upstream_connect_time '
'uht=$upstream_header_time ut=$upstream_response_time';
access_log /var/log/nginx/access.log detailed;
关键字段含义:
request_time:Nginx 处理整个请求的时间upstream_response_time:后端处理时间request_time 大但 upstream_response_time 小 → Nginx 或网络问题upstream_response_time 大 → 后端慢# 请求时间超过 1 秒
awk '$NF > 1' /var/log/nginx/access.log
# 按 URL 聚合平均耗时
awk '{print $7, $NF}' access.log | sort | uniq -c
location /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}
关注:
Active connectionsReading / Writing / Waiting如果 Writing 很高,说明响应慢。
sendfile)gzip 配置不合理proxy_buffering 关闭检查:
sendfile on;
tcp_nopush on;
gzip on;
proxy_read_timeout 60s;
proxy_connect_timeout 5s;
keepalive_timeout 65s;
如果 upstream_connect_time 高:
slowlog)如果:
ut=2.5s
rt=2.5s
✅ 明确是后端慢
top
iostat -x 1
netstat -an | grep :80 | wc -l
常见问题:
tcpdump -i eth0 port 80 -w nginx.pcap
看:
| 现象 | 可能原因 |
|---|---|
| rt 大,ut 小 | Nginx / 网络 |
| ut 大 | 后端慢 |
| Writing 高 | 响应慢 |
| connect time 高 | 后端不可用 |
| CPU 高 | 配置或流量问题 |
如果你愿意,可以:
我可以帮你更精确地定位。