要从日志排查 Nginx 瓶颈,通常分三步:看访问日志、看错误日志、结合系统指标。下面给你一套实用思路(偏运维实战)。
默认位置:
/var/log/nginx/access.log
常见格式:
$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"
如果没记录时间、响应时间,建议开启:
log_format main '$remote_addr - $time_local "$request" '
'$status $body_bytes_sent $request_time $upstream_response_time';
重点字段:
request_time:整体请求耗时upstream_response_time:后端耗时(如果是反向代理)awk '{print $NF, $0}' access.log | sort -rn | head -10
($NF 假设是 request_time,按实际格式调整)
或:
grep -o 'request_time=[0-9.]*' access.log | sort -rn | head
比如超过 1 秒的:
awk '$NF > 1 {c++} END {print c}' access.log
常见判断:
request_time 大,upstream_response_time 小 → Nginx 本身或网络问题upstream_response_time 为 - → 没走到后端(静态资源 or 配置问题)/var/log/nginx/error.log
重点看:
too many open files
upstream timed out
connect() failed
502 / 504
worker_connections are not enough
常见瓶颈信号:
too many open files → 文件描述符不够upstream timed out → 后端瓶颈worker_connections 满 → 并发能力不足location /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}
查看:
curl http://127.0.0.1/nginx_status
关注:
Active connectionsRequests per secondReading / Writing / Waiting判断:
Waiting 很高 → 连接池或 keepalive 问题top
htop
iostat -x 1
netstat -an | grep :80 | wc -l
看:
| 现象 | 可能瓶颈 |
|---|---|
| request_time 大,upstream 小 | Nginx / 网络 |
| upstream 大 | 后端服务 |
| 502/504 多 | 后端或超时配置 |
| open files 报错 | 系统 ulimit |
| Waiting 很高 | keepalive / 客户端 |
| CPU 高 | 静态资源 / 正则 location |
如果你愿意,可以把 一段 access.log + error.log 发我,我可以直接帮你判断是 Nginx 还是后端的问题。