基于Gunicorn和Nginx部署Flask-Vue站点遇连接超时问题求助
问题:Flask+Vue部署后前后端通信失败
背景
接手同事开发的Flask+Vue网站,本地调试正常,部署到服务器后前端可正常加载,但无法与后端接口通信。
已执行操作
Gunicorn启动命令
gunicorn --workers 1 --bind 0.0.0.0:5000 -m 777 wsgi:app
Nginx配置
server { listen 80; server_name 192.168.1.1; add_header Access-Control-Allow-Origin *; # 允许静态页面接收POST请求 error_page 405 =200 $uri; location / { root frontend/dist; try_files $uri $uri/ /index.html; } location /config { include proxy_params; proxy_pass http://0.0.0.0:5000; } }
前端后端地址配置(App.vue)
曾尝试两种写法:
backend_url: 'http://127.0.0.1:5000' backend_url: 'http://192.168.1.1:5000'
报错信息
- Chrome控制台:
POST http://192.168.1.1:5000/config net::ERR_CONNECTION_TIMED_OUT 192.168.1.1/:1 Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received - Firefox控制台:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.1:5000/config. (Reason: CORS request did not succeed). Status code: (null)
已尝试的CORS配置
Flask端
app = Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type' cors = CORS(app, resources={r"/*": {"origins": "*"}})
Nginx端
已添加add_header Access-Control-Allow-Origin *;
解决方案
修正前端请求地址
前端应通过Nginx代理访问后端,而非直接请求Gunicorn的5000端口。修改App.vue中的地址:backend_url: '/config'这样请求会自动匹配Nginx的
/config规则转发到后端,彻底避免跨域和端口直连问题。优化Nginx代理配置
- 将
proxy_pass的目标地址改为http://127.0.0.1:5000(服务器本地回环地址),比0.0.0.0更稳定,避免多网卡绑定冲突。 - 检查
proxy_params文件,确保包含Host $host、X-Real-IP $remote_addr等必要头部,否则后端可能无法正确识别请求来源。
- 将
检查服务器防火墙
服务器防火墙可能禁止了5000端口的外部访问,导致前端直接请求192.168.1.1:5000超时。推荐通过Nginx代理访问后端(无需开放5000端口),若必须开放,需在防火墙中添加允许规则。验证Gunicorn运行状态
执行ps aux | grep gunicorn确认Gunicorn是否正常运行,且确实绑定在5000端口。如果Gunicorn未启动或绑定失败,Nginx代理会直接报错。调整CORS配置(可选)
若使用Nginx代理,前端请求与Nginx同域,无需额外配置跨域。如果保留Flask的CORS配置,需注意Nginx的add_header仅在响应码为200、201、204等特定状态码时生效,若后端返回其他状态码,需在Nginx的对应location中补充add_header规则。
内容的提问来源于stack exchange,提问作者user2739347
相关产品推荐
相关产品推荐

