Docker部署Flask+Gunicorn遭遇502 Bad Gateway错误求助
Flask+Docker部署出现502 Bad Gateway的修复方案
核心问题分析
你的Nginx配置中proxy_pass缺少http://前缀,导致Nginx将127.0.0.1:8000识别为本地文件路径而非TCP地址,无法连接到Gunicorn服务,从而返回502错误。此外,容器内进程管理方式也存在潜在稳定性问题。
分步修复
1. 修正Nginx配置文件
修改nginx.conf中的proxy_pass配置,添加http://前缀,或直接使用已定义的upstream名称(更规范):
upstream flask-app { server 127.0.0.1:8000; } server { listen 80; server_name localhost; location / { # 推荐使用upstream名称 proxy_pass http://flask-app; # 也可直接指定带http前缀的地址:proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; } }
同时将proxy_set_header Host "localhost"改为$host,适配不同访问场景。
2. 调整Gunicorn绑定地址
将Gunicorn绑定到容器所有网络接口(0.0.0.0),确保服务可被容器内Nginx正常访问:
在Dockerfile的CMD中添加-b 0.0.0.0:8000参数:
CMD /etc/init.d/nginx start && gunicorn -w 3 -b 0.0.0.0:8000 app:app --timeout 900 --preload
3. 优化容器进程管理(可选但推荐)
使用前台方式运行Nginx,配合supervisor同时管理Nginx和Gunicorn进程,避免后台进程意外退出:
步骤1:在Dockerfile中安装supervisor
RUN apt-get update && apt-get install -y nginx supervisor
步骤2:创建supervisord.conf配置文件
[supervisord] nodaemon=true [program:nginx] command=/usr/sbin/nginx -g "daemon off;" autostart=true autorestart=true [program:gunicorn] command=gunicorn -w 3 -b 0.0.0.0:8000 app:app --timeout 900 --preload directory=/app autostart=true autorestart=true
步骤3:修改Dockerfile替换启动命令
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf CMD ["supervisord"]
验证修复
重新构建镜像并启动容器:
docker build -t flask-app . docker run -p 80:80 flask-app
访问http://localhost即可正常访问Flask应用。
内容的提问来源于stack exchange,提问作者Mohamed Hasan
相关产品推荐
相关产品推荐

