EC2部署Flask应用:Nginx未转发至Gunicorn及公网IP访问异常
AWS EC2部署Flask应用:Nginx转发失败&公网访问8000端口问题修复
核心问题分析
- 公网直接访问
<public_ip>:8000失败:Gunicorn绑定的是localhost:8000,仅监听服务器本地回环接口,外部请求根本连不上这个端口。 - Nginx未正确转发请求:配置里的
try_files指令会优先查找本地静态文件,找不到就直接返回404,不会把动态请求转发给Gunicorn。
具体修复步骤
1. 调整Gunicorn监听设置(可选,按需选择)
如果非要直接通过公网访问8000端口,修改Gunicorn服务配置文件(通常路径为/etc/systemd/system/gunicorn.service):
[Unit] Description=Gunicorn instance for a simple hello world app After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/algotrading/oops ExecStart=/home/ubuntu/algotrading/venv/bin/gunicorn -b 0.0.0.0:8000 wsgi:app Restart=always [Install] WantedBy=multi-user.target
更新服务配置并重启Gunicorn:
sudo systemctl daemon-reload sudo systemctl restart gunicorn
同时在AWS安全组中添加8000端口的入站规则,允许所有外部IP访问。
不过更规范的做法是通过Nginx转发请求,不直接暴露Gunicorn,建议优先用下面的Nginx修复方案。
2. 修复Nginx转发配置
编辑/etc/nginx/sites-available/default文件,更新location /块内容:
location / { proxy_pass http://127.0.0.1:8000; # 传递必要的请求头给Flask应用,确保应用能正确识别请求信息 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; }
- 删除原有的
try_files $uri $uri/ =404;,避免拦截动态请求 - 添加代理头,保证Flask应用能获取到请求的Host、IP等关键信息
验证Nginx配置是否合法:
sudo nginx -t
如果提示配置有效,重启Nginx服务:
sudo systemctl restart nginx
3. 配置AWS安全组开放80端口
公网访问时,使用http://<public_ip>/oops/configuration/fetchConfigurations?schema=oops1_v1_sit(默认80端口,由Nginx处理转发),因此需要在AWS安全组中添加80端口的入站规则,允许所有外部IP访问。
验证修复效果
- 服务器本地测试Nginx转发是否正常:
curl http://127.0.0.1/oops/configuration/fetchConfigurations?schema=oops1_v1_sit
- 公网访问测试:直接在浏览器或本地终端访问上述公网地址
内容的提问来源于stack exchange,提问作者Abhishek Gaur
相关产品推荐
相关产品推荐

