温馨提示×

如何定位nginx慢请求

小樊
44
2026-09-26 19:46:41
栏目: 编程语言

定位 Nginx 慢请求,通常可以从 请求链路分层排查:客户端 → Nginx → 后端(如 PHP/Java/Node) → 数据库/外部服务。下面按实战步骤说明。


一、先确认:是 Nginx 慢,还是后端慢

1. 开启 Nginx 请求耗时日志(最关键)

在 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 大 → 后端慢

二、常见慢请求定位方法

2. 用 access log 找慢请求

# 请求时间超过 1 秒
awk '$NF > 1' /var/log/nginx/access.log

# 按 URL 聚合平均耗时
awk '{print $7, $NF}' access.log | sort | uniq -c

3. 查看 Nginx 状态(stub_status)

location /nginx_status {
    stub_status on;
    allow 127.0.0.1;
    deny all;
}

关注:

  • Active connections
  • Reading / Writing / Waiting

如果 Writing 很高,说明响应慢。


三、Nginx 自身可能慢的原因

4. 静态资源 & 配置问题

  • 大文件下载(未用 sendfile)
  • gzip 配置不合理
  • proxy_buffering 关闭
  • TLS 握手慢(证书链过长)

检查:

sendfile on;
tcp_nopush on;
gzip on;

5. 反向代理相关

proxy_read_timeout 60s;
proxy_connect_timeout 5s;
keepalive_timeout 65s;

如果 upstream_connect_time 高:

  • 后端端口不通
  • 后端连接池满

四、后端慢的定位(非常常见)

6. 后端响应时间分析

  • PHP:慢日志(slowlog)
  • Java:APM(SkyWalking / Arthas)
  • Node:CPU profile

如果:

ut=2.5s
rt=2.5s

✅ 明确是后端慢


五、系统级排查

7. 系统资源

top
iostat -x 1
netstat -an | grep :80 | wc -l

常见问题:

  • CPU 100%
  • 磁盘 IO 高
  • 连接数打满

六、高级手段(可选)

8. 抓包分析

tcpdump -i eth0 port 80 -w nginx.pcap

看:

  • TCP 重传
  • 延迟 ACK
  • TLS 握手慢

9. 使用 APM / tracing

  • Nginx + OpenTelemetry
  • SkyWalking
  • Prometheus + Grafana

七、快速判断总结表

现象 可能原因
rt 大,ut 小 Nginx / 网络
ut 大 后端慢
Writing 高 响应慢
connect time 高 后端不可用
CPU 高 配置或流量问题

如果你愿意,可以:

  • 贴一段 access log
  • 或说明 Nginx 是做静态还是反向代理
  • 或后端是什么语言

我可以帮你更精确地定位。

0 踩