Appearance
常见错误排查
本节介绍Nginx常见错误及其排查方法。
启动失败
端口被占用
错误信息:
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)排查方法:
bash
# 查看占用80端口的进程
sudo netstat -tlnp | grep :80
# 查看占用80端口的进程
sudo lsof -i :80解决方法:
bash
# 停止占用80端口的进程
sudo kill -9 <PID>
# 或者修改Nginx监听端口
listen 8080;配置文件错误
错误信息:
nginx: [emerg] invalid number of arguments in "worker_processes" directive排查方法:
bash
# 测试配置文件
sudo nginx -t解决方法:
bash
# 修复配置文件错误
worker_processes auto;权限不足
错误信息:
nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)排查方法:
bash
# 检查Nginx用户
ps aux | grep nginx解决方法:
bash
# 使用sudo启动
sudo nginx
# 或者修改监听端口为1024以上
listen 8080;运行时错误
502 Bad Gateway
错误信息:
502 Bad Gateway排查方法:
bash
# 查看错误日志
sudo tail -f /var/log/nginx/error.log
# 检查后端服务器是否运行
curl http://backend:8080解决方法:
nginx
# 增加超时时间
proxy_connect_timeout 60;
proxy_send_timeout 60;
proxy_read_timeout 60;
# 检查后端服务器配置
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}504 Gateway Timeout
错误信息:
504 Gateway Timeout排查方法:
bash
# 查看错误日志
sudo tail -f /var/log/nginx/error.log
# 检查后端服务器响应时间
time curl http://backend:8080解决方法:
nginx
# 增加超时时间
proxy_connect_timeout 120;
proxy_send_timeout 120;
proxy_read_timeout 120;403 Forbidden
错误信息:
403 Forbidden排查方法:
bash
# 检查文件权限
ls -l /var/www/html
# 检查Nginx用户
ps aux | grep nginx解决方法:
bash
# 修改文件权限
sudo chown -R nginx:nginx /var/www/html
sudo chmod -R 755 /var/www/html
# 检查Nginx配置
user nginx;404 Not Found
错误信息:
404 Not Found排查方法:
bash
# 检查文件是否存在
ls -l /var/www/html/index.html
# 检查root配置
grep "root" /etc/nginx/nginx.conf解决方法:
nginx
# 修改root配置
root /var/www/html;
# 检查try_files配置
location / {
try_files $uri $uri/ =404;
}性能问题
响应慢
排查方法:
bash
# 查看响应时间
curl -w "@curl-format.txt" -o /dev/null -s http://example.com
# 查看Nginx状态
curl http://localhost/nginx_status解决方法:
nginx
# 启用缓存
proxy_cache on;
# 启用Gzip
gzip on;
# 优化worker进程
worker_processes auto;
worker_connections 4096;CPU占用高
排查方法:
bash
# 查看CPU占用
top -p $(pgrep nginx)
# 查看Nginx进程
ps aux | grep nginx解决方法:
nginx
# 减少worker进程
worker_processes 2;
# 降低Gzip压缩级别
gzip_comp_level 4;内存占用高
排查方法:
bash
# 查看内存占用
free -h
# 查看Nginx进程
ps aux | grep nginx解决方法:
nginx
# 减少缓冲区大小
client_body_buffer_size 128k;
proxy_buffers 8 4k;常见问题
配置修改不生效
原因: 未重新加载配置
解决:
bash
# 测试配置
sudo nginx -t
# 重新加载配置
sudo nginx -s reload日志文件过大
原因: 日志记录过多
解决:
bash
# 配置日志轮转
sudo vi /etc/logrotate.d/nginx
# 或使用条件日志
map $request_uri $loggable {
~* \.(jpg|jpeg|png|gif|css|js)$ 0;
default 1;
}
access_log /var/log/nginx/access.log main if=$loggable;总结
常见错误排查的关键点:
- 启动失败:检查端口、配置文件、权限
- 运行时错误:查看错误日志,检查后端服务器
- 性能问题:优化配置,启用缓存和压缩
- 配置修改不生效:重新加载配置
- 日志文件过大:配置日志轮转或使用条件日志
掌握常见错误排查方法,快速解决Nginx问题。