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

Ubuntu20.04部署Flask+uWSGI+Nginx遇502错误求解决

Flask + uWSGI + Nginx 部署出现502 Bad Gateway错误(Ubuntu 20.04)

按照DigitalOcean教程在Ubuntu 20.04服务器部署Flask项目,搭配uWSGI与Nginx时出现**502 Bad Gateway(nginx/1.18.0 (Ubuntu))**错误。

Nginx错误日志内容如下:

upstream prematurely closed connection while reading response header from upstream, client: 93.37.157.148, server: 3.75.132.146, request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://unix:/home/ubuntu/flask-app/webapp/flask-app.sock:", host: "3.75.132.146", referrer: "http://3.75.132.146/"

当前配置文件

uWSGI配置文件

[uwsgi]
module = wsgi:app
wsgi-file = /home/ubuntu/flask-app/webapp/wsgi.py
chdir = /home/ubuntu/flask-app/webapp/
protocol = http
#home = /usr/local/lib/python3.8/dist-packages/

master = true
processes = 5

limit-as = 512
uid = ubuntu
gid = www-data
socket = flask-app.sock

chown-socket = ubuntu
chmod-socket = 777
vacuum = true

die-on-term = true

Nginx配置文件

server {
    listen 80;
    server_name 3.75.132.146;

    location /static {
        alias /home/ubuntu/flask-app/webapp/static/;
    }
    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/ubuntu/flask-app/webapp/flask-app.sock;
    }
}

解决方案步骤

  • 修正uWSGI协议配置:Nginx通过uwsgi_pass与uWSGI通信,要求uWSGI使用uwsgi协议,但当前配置里写的是protocol = http,这会导致通信不兼容。把这一行改成protocol = uwsgi,或者直接注释/删除该行(uWSGI默认协议就是uwsgi)。

  • 配置虚拟环境路径:当前uWSGI的home参数被注释,需要将其指向你的Flask项目虚拟环境的实际路径(比如如果用venv创建的虚拟环境,路径可能是/home/ubuntu/flask-app/webapp/venv),确保uWSGI能加载项目依赖。

  • 确保socket目录权限正确:虽然设置了socket的权限为777,但要保证Nginx运行用户(www-data)能访问socket所在的目录。执行命令:

    chmod +x /home/ubuntu/flask-app/webapp/
    
  • 重启服务:修改配置后,重启uWSGI和Nginx使配置生效:

    sudo systemctl restart uwsgi
    sudo systemctl restart nginx
    
  • 验证uWSGI运行状态:用以下命令检查uWSGI是否正常启动:

    ps aux | grep uwsgi
    

    如果没有进程,查看uWSGI的启动日志(通常在/var/log/uwsgi/或自定义路径)排查启动错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:15:16