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

使用Nginx+uWSGI部署Flask应用遇502错误,求原因排查

Nginx+uWSGI部署Flask返回502错误的排查与修复

测试Flask应用部署时触发assert 502 == 200错误,说明Nginx返回了502 Bad Gateway,本质是Nginx无法正常连接后端的uWSGI服务,以下是具体排查点和修复方案:

你的配置代码

deploy.conf

server {
    listen 8000;

    location /Hello { 
        include uwsgi_params; 
        uwsgi_pass localhost:8081; 
    }
}

api.py

from flask import Flask, request, make_response

app = Flask(__name__)
app.secret_key = "Thisisyoursecret"

@app.route('/Hello')
def hello():
    res=make_response("Welcome to your flask application")
    return res

if __name__ == "__main__":
    app.run(host='0.0.0.0')

uwsgi.ini

[uwsgi]
socket = 127.0.0.1:8081
module = wsgi:app
master = true
processes = 5

wsgi.py

from api import app
if __name__ == "__main__":
    app.run()

测试用例

def test_hello_from_nginx_server(self):
    url = "http://localhost:8000/Hello"
    response = requests.get(url)
    assert response.status_code == 200
    assert response.text == 'Welcome to your flask application'

排查与修复步骤

  1. 确认uWSGI服务是否正常启动

    • 执行启动命令:uwsgi --ini uwsgi.ini,观察终端输出是否有报错(比如找不到api模块、无法绑定socket)。
    • 若启动失败,检查wsgi.py和api.py是否在同一目录,或者在uwsgi.ini中添加chdir = /你的项目绝对路径指定工作目录,确保uWSGI能找到Flask应用。
  2. 修正Nginx的后端连接配置
    你的uWSGI监听的是IPv4的127.0.0.1:8081,但Nginx中用localhost可能解析到IPv6的::1,导致连接失败。将deploy.conf中的:

    uwsgi_pass localhost:8081;
    

    修改为:

    uwsgi_pass 127.0.0.1:8081;
    

    改完后执行nginx -s reload重新加载Nginx配置。

  3. 查看Nginx错误日志定位具体原因
    查看Nginx错误日志(通常路径是/var/log/nginx/error.log),如果日志中出现connect() failed (111: Connection refused) while connecting to upstream,说明uWSGI未启动或端口不匹配;如果是no such file or directory,则是socket路径配置错误。

  4. 验证修复效果
    重启uWSGI和Nginx,再次运行测试用例,应该能返回200状态码并通过断言。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 23:15:19