Ubuntu服务器上Django+Gunicorn出现502 Bad Gateway错误求助
Django+Gunicorn+Nginx 502 Bad Gateway 问题排查方案
1. 确认Gunicorn正常监听8000端口
- 执行命令检查端口占用:
sudo lsof -i :8000或者sudo netstat -tulpn | grep 8000 - 如果没有Gunicorn进程监听,说明手动启动的Gunicorn未正常运行,检查启动命令是否正确,比如是否指定了正确的Django项目目录、wsgi模块:
示例启动命令:gunicorn --bind 127.0.0.1:8000 your_project.wsgi:application - 查看Gunicorn启动时的终端输出,排查是否有依赖缺失、项目配置错误等直接报错。
2. 检查Nginx与Gunicorn的通信权限
- Ubuntu下Nginx默认以
www-data用户运行,确保该用户有权限访问127.0.0.1:8000端口 - 临时关闭防火墙测试:
sudo ufw disable(测试完成后记得重新开启) - 如果启用了SELinux,执行:
sudo setsebool -P httpd_can_network_connect 1开放网络连接权限
3. 优化Nginx配置
你的当前配置可补充必要请求头,避免转发异常,调整后配置如下:
upstream django { server 127.0.0.1:8000; keepalive 64; } server { listen 80; listen [::]:80; server_name qhse-erp.com www.qhse-erp.com; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_pass http://django; } }
- 重启Nginx使配置生效:
sudo systemctl restart nginx
4. 排查系统资源与套接字问题
- 检查系统文件描述符上限:
ulimit -n,如果数值过低,编辑/etc/security/limits.conf添加:* soft nofile 65536 * hard nofile 65536 - 若TCP套接字TIME_WAIT状态过多,编辑
/etc/sysctl.conf添加:
执行net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_tw_recycle = 1 net.ipv4.tcp_fin_timeout = 30sudo sysctl -p使参数生效
5. 查看详细错误日志定位根源
- 实时监控Nginx错误日志:
tail -f /var/log/nginx/error.log,访问网站后查看是否有连接拒绝、超时等具体报错 - Gunicorn手动启动时直接查看终端输出;后续做成服务后,可查看自定义日志路径或
/var/log/gunicorn/下的日志文件
内容的提问来源于stack exchange,提问作者Youssri Abo Elseod
相关产品推荐
相关产品推荐

