【问题标题】:Nginx, Flask, Gunicorn 502 ErrorNginx、Flask、Gunicorn 502 错误
【发布时间】:2025-12-11 02:05:01
【问题描述】:

我对 Flask/Nginx/Gunicorn 还是很陌生,因为这只是我使用该组合的第二个站点。我根据 Miguel Grinberg 的 tutorial 创建了一个网站,因此我的文件结构与本教程中的完全相同。

在我之前的 Flask 应用程序中,我的应用程序位于一个名为 app.py 的文件中,所以当我使用 Gunicorn 时,我只调用了
gunicorn app:app

现在我的新应用程序被拆分为多个文件,我使用文件run.py 来启动应用程序,但我不确定现在应该如何调用 Gunicorn。我已经阅读了其他问题和教程,但它们没有奏效。当我运行 gunicorn run:app 并尝试访问该站点时,我收到 502 Bad Gateway 错误。

我认为我的问题更多是 Gunicorn,而不是 Nginx 或 Flask,因为如果我只输入 ./run.py,该网站就可以工作。无论如何,我在下面包含了我的 Nginx 配置和其他一些文件。非常感谢您的帮助!

文件:run.py

#!flask/bin/python
from app import app
from werkzeug.contrib.fixers import ProxyFix

app.wsgi_app = ProxyFix(app.wsgi_app)
app.run(debug = True, port=8001)

文件:app/views.py

from app import app

@app.route('/')
@app.route('/index')
def index():
    posts = Post.query.order_by(Post.id.desc()).all()
    return render_template('index.html', posts=posts)

文件:nginx.conf

server {
    listen 80;
    server_name example.com;

    root /var/www/example.com/public_html/app;

    access_log /var/www/example.com/logs/access.log;
    error_log /var/www/example.com/logs/error.log;

    client_max_body_size 2M;

    location / {
        try_files $uri @gunicorn_proxy;
    }

    location @gunicorn_proxy {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:8001;
    }
}

【问题讨论】:

  • 您确认您可以访问127.0.0.1:8001 了吗?然后 - 我会将“location @gunicorn_proxy”更改为“location /”(并注释掉之前的位置部分)
  • @soerium 我可以访问 127.0.0.1:8001,因为当我从命令行运行我的应用程序时,Flask 会打印 * Running on http://127.0.0.1:8001

标签: python nginx flask gunicorn


【解决方案1】:

当 gunicorn 导入 app.py 时,开发服务器正在运行。您只希望在直接执行文件时发生这种情况(例如,python app.py)。

#!flask/bin/python
from app import app
from werkzeug.contrib.fixers import ProxyFix

app.wsgi_app = ProxyFix(app.wsgi_app)

if __name__ == '__main__':
    # You don't need to set the port here unless you don't want to use 5000 for development.
    app.run(debug=True)

完成此更改后,您应该可以使用gunicorn run:app 运行应用程序。请注意,gunicorn 默认使用端口 8000。如果您希望在备用端口(例如 8001)上运行,则需要使用 gunicorn -b :8001 run:app 指定。

【讨论】:

  • 感谢您回复我。我尝试更改run.py 以包含您建议的if 语句,如果我直接从命令执行它,例如$ ./run.py,但如果我尝试gunicorn $gunicorn rup:app,则不会。
  • 哎呀,这是一个错字。当我输入 $ gunicorn run:app 时,Gunicorn 似乎不起作用。
  • 我更新了答案以包含有关指定端口的信息。