温馨提示×

怎样从日志查nginx瓶颈

小樊
42
2026-10-23 04:22:08
栏目: 编程语言

要从日志排查 Nginx 瓶颈,通常分三步:看访问日志、看错误日志、结合系统指标。下面给你一套实用思路(偏运维实战)。


一、先确认看哪几个日志

1. Nginx 访问日志(access.log)

默认位置:

/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:后端耗时(如果是反向代理)

二、从访问日志找“慢请求”

1. 找出最慢的 10 个请求

awk '{print $NF, $0}' access.log | sort -rn | head -10

($NF 假设是 request_time,按实际格式调整)

或:

grep -o 'request_time=[0-9.]*' access.log | sort -rn | head

2. 统计慢请求比例

比如超过 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 满 → 并发能力不足

四、结合 Nginx 状态模块(强烈推荐)

开启 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
  • Requests per second
  • Reading / Writing / Waiting

判断:

  • Waiting 很高 → 连接池或 keepalive 问题
  • 连接数持续打满 → worker 数或系统限额问题

五、系统层辅助判断

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

看:

  • CPU 是否跑满
  • 磁盘 IO 是否瓶颈
  • 网络连接数是否异常

六、常见瓶颈结论速查表

现象 可能瓶颈
request_time 大,upstream 小 Nginx / 网络
upstream 大 后端服务
502/504 多 后端或超时配置
open files 报错 系统 ulimit
Waiting 很高 keepalive / 客户端
CPU 高 静态资源 / 正则 location

如果你愿意,可以把 一段 access.log + error.log 发我,我可以直接帮你判断是 Nginx 还是后端的问题。

0 踩