通过日志来优化 Nginx 性能,核心思路是:用日志发现问题 → 定位瓶颈 → 调整配置或架构 → 验证效果。下面按“可操作步骤 + 实战要点”来说明。
log_format默认日志信息太少,建议自定义:
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time $upstream_addr';
关键字段:
request_time:整体请求耗时upstream_response_time:后端耗时(反向代理场景)upstream_addr:后端地址access_log off;location ~* \.(jpg|css|js|png)$ {
access_log off;
}
map $status $loggable {
default 1;
200 0;
}
access_log /var/log/nginx/access.log main if=$loggable;
awk '{print $NF, $7}' access.log | sort -rn | head
或专门看 request_time:
awk '{print $request_time, $request}' access.log | sort -rn | head
判断标准(经验值):
< 0.1s:正常0.1–0.5s:需注意> 1s:明显问题对比:
request_timeupstream_response_time| 情况 | 说明 |
|---|---|
| request_time 大,upstream 小 | Nginx 或网络问题 |
| 两者都大 | 后端慢 |
| upstream 为空 | 静态或缓存命中 |
awk '{print $9}' access.log | sort | uniq -c | sort -rn
常见问题:
499:客户端超时(Nginx 太快 or 后端太慢)502/504:后端不稳定404:资源配置错误如果 upstream_response_time 高:
proxy_cache_path /data/cache levels=1:2 keys_zone=mycache:10m;
location /api/ {
proxy_cache mycache;
proxy_cache_valid 200 10m;
}
location ~* \.(js|css|png)$ {
expires 7d;
access_log off;
}
日志中出现大量并发或 502:
worker_processes auto;
worker_connections 10240;
日志中 POST 大请求慢:
client_max_body_size 10m;
goaccess access.log -o report.html
/api/user 平均 1.2supstream_response_time = 1.1sproxy_cache如果你愿意,可以:
我可以直接帮你“看日志 + 给优化方案”。