温馨提示×

怎样定位debian nginx慢请求

小樊
39
2026-10-04 07:54:32
栏目: 智能运维

在 Debian 上定位 Nginx 慢请求(slow request),通常可以从 Nginx 自身日志、系统层面、后端应用、网络 四个方向入手。下面给你一套实用、可操作的排查思路。


一、先确认“慢”发生在哪一层

慢请求不一定在 Nginx:

  • 客户端 → Nginx(网络/TLS)
  • Nginx → 后端(PHP/Java/Python)
  • Nginx 自身处理(rewrite、大文件、limit)

二、开启并分析 Nginx 慢日志(最关键)

1. 开启 request_time / upstream_response_time

编辑站点配置(如 /etc/nginx/sites-enabled/default):

log_format main '$remote_addr - $remote_user [$time_local] '
                '"$request" $status '
                'rt=$request_time uct=$upstream_connect_time '
                'uht=$upstream_header_time urt=$upstream_response_time';

access_log /var/log/nginx/access.log main;

重载 Nginx:

nginx -t
systemctl reload nginx

字段含义:

  • rt:总请求耗时(客户端视角)
  • urt:后端处理耗时
  • 如果 rt 大但 urt 小 → Nginx 或网络问题
  • 如果 urt 大 → 后端慢

2. 找出慢请求

awk '$NF > 2 {print}' /var/log/nginx/access.log

或按时间排序:

sort -k12 -n /var/log/nginx/access.log | tail

三、定位是否有“卡住”的请求

1. 查看当前连接状态

nginx -V 2>&1 | grep stub_status

若支持,开启:

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

访问:

curl http://127.0.0.1/nginx_status

关注:

  • Active connections
  • Reading / Writing / Waiting

2. 查看 Nginx worker 状态

ps -eo pid,ppid,cmd,%cpu,%mem,etime | grep nginx

如果有 worker 长时间不退出 → 可能阻塞。


四、系统层面排查

1. 看 CPU / IO / 内存

top
iostat -x 1
vmstat 1

常见问题:

  • 磁盘 IO 高(access log 写入)
  • CPU 软中断高(网络)

2. 看网络连接

ss -tnp | grep nginx

关注:

  • ESTABLISHED 很多但无数据
  • TIME_WAIT 过多

五、后端慢(最常见)

1. PHP(示例)

php-fpm.conf
request_slowlog_timeout = 2s
slowlog = /var/log/php-fpm/slow.log

查看慢日志:

tail -f /var/log/php-fpm/slow.log

2. 反向代理(Java/Python)

  • 后端接口直接 curl 测试:
curl -w "%{time_total}\n" http://127.0.0.1:8080/api

六、TLS / 网络慢

1. HTTPS 握手慢

curl -w "%{time_connect} %{time_starttransfer} %{time_total}\n" https://domain

2. DNS 解析慢

Nginx 中避免使用外部域名做 proxy_pass,或加:

resolver 127.0.0.1 valid=10s;

七、常见“坑”

  • access_log 没加 request_time
  • proxy_buffering off 导致响应变慢
  • 开启了 gzip 但 CPU 不够
  • 大量 404 静态资源请求
  • 防火墙 / 安全模块(modsecurity)

八、快速定位 checklist(总结)

  1. ✅ 开启 request_time + upstream_response_time
  2. ✅ 找出 rt > 1s 的请求
  3. ✅ 对比 rt 和 urt
  4. ✅ 查后端慢日志
  5. ✅ 看系统 CPU / IO / 网络
  6. ✅ 排除 TLS / DNS

如果你愿意,可以把:

  • Nginx 版本
  • 是否反代
  • 后端类型(PHP / Java / Node)
  • 慢请求示例日志

发出来,我可以帮你 精准定位是哪一层慢。

0 踩