You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EC2部署Django遇502 Bad Gateway(13 permission denied)问题求助

解决Django部署中Nginx 502 Bad Gateway (13 permission denied)问题

核心原因排查

你的场景中,尽管sock文件及目录的属主已设为ubuntu:www-data,但大概率是主目录权限限制或sock文件访问权限不足导致Nginx无法访问套接字资源。

具体解决方案

1. 修复/home/ubuntu目录的访问权限

Ubuntu默认用户主目录/home/ubuntu的权限为700,仅允许ubuntu用户自身进入,Nginx运行用户www-data无法穿透该目录访问子资源。执行以下命令开放主目录的执行权限:

chmod 710 /home/ubuntu

该设置既保证主目录内容不被其他用户读取,又允许www-data用户进入目录访问子文件。

2. 强制设置Gunicorn生成的sock文件权限

Gunicorn默认生成的Unix套接字权限为600,仅运行它的ubuntu用户可读写,www-data用户无访问权限。修改Gunicorn的systemd配置,添加UMask参数强制调整sock权限:
编辑Gunicorn服务配置文件(如/etc/systemd/system/gunicorn.service),在[Service]块中新增:

UMask=0007

修改后的[Service]块示例:

[Service]
User=ubuntu
Group=www-data
UMask=0007
WorkingDirectory=/home/ubuntu/sites/mysite-main
ExecStart=/home/ubuntu/.local/share/virtualenvs/mysite-main-_EzVOJAm/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/sites/mysite-main/mysite-main.sock myapp.wsgi:application

执行命令重载配置并重启服务:

sudo systemctl daemon-reload
sudo systemctl restart gunicorn

此时生成的sock文件权限会变为660,www-data用户组可正常读写。

3. 解决sock移至公共目录无法生成的问题

若想将sock放到/run这类公共目录(推荐,彻底规避主目录权限问题),需确保Gunicorn拥有目录写入权限:

  • 创建专属目录并设置权限:
sudo mkdir /run/gunicorn/
sudo chown ubuntu:www-data /run/gunicorn/
sudo chmod 775 /run/gunicorn/
  • 修改Gunicorn配置中的--bind路径:
ExecStart=/home/ubuntu/.local/share/virtualenvs/mysite-main-_EzVOJAm/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn/mysite-main.sock myapp.wsgi:application
  • 修改Nginx配置中的proxy_pass路径:
proxy_pass http://unix:/run/gunicorn/mysite-main.sock;
  • 重载配置并重启服务:
sudo systemctl daemon-reload
sudo systemctl restart gunicorn
sudo systemctl restart nginx

4. 验证Nginx访问权限

执行以下命令模拟www-data用户访问sock文件,确认权限是否正常:

sudo -u www-data ls -l /home/ubuntu/sites/mysite-main/mysite-main.sock

若能正常列出文件,说明权限配置有效;若报错,回到前面步骤检查目录及文件权限。

内容的提问来源于stack exchange,提问作者Raiden616

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:20:20