python - 使用 nginx 和 gunicorn 运行 flask 应用程序

标签 python nginx flask gunicorn

我是新手,只使用 nginx 来提供静态文件。我现在已经安装了 flask 和 gunicorn。如果我运行 gunicorn -b 127.0.0.2:8000 hello:app 然后从服务器 wget 它运行良好。但是,如果我尝试从浏览器访问它,它会返回 404 错误(我在托管位于根目录的 wordpress 站点的服务器上运行它)。

flask 应用:

from flask import Flask
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello world!"

app.wsgi_app = ProxyFix(app.wsgi_app)

if __name__ == '__main__':
    app.run()

以及我的 nginx 配置的相关部分:

location /flask {
                 proxy_set_header       Host            $http_host;
                 proxy_set_header       X-Real-IP       $remote_addr;
                 proxy_set_header       X-Forwarded-For $proxy_add_x_forwarded_\
for;
                 proxy_pass             http://127.0.0.2:8000;
                 proxy_redirect         off;
    }

我希望这是所有相关信息。如果没有,请告诉。谢谢!

最佳答案

这就是我在 Nginx 中提供 flask 应用程序的方式:

使用套接字运行 gunicorn 守护进程:

  sudo gunicorn app:app --bind unix:/tmp/gunicorn_flask.sock -w 4 -D

相关的nginx配置:

    upstream flask_server {
        # swap the commented lines below to switch between socket and port
        server unix:/tmp/gunicorn_flask.sock fail_timeout=0;
        #server 127.0.0.1:5000 fail_timeout=0;
    }
    server {
        listen 80;
        server_name www.example.com;
        return 301 $scheme://example.com$request_uri;
    }

    server {
        listen 80;
        client_max_body_size 4G;
        server_name example.com;

        keepalive_timeout 5;

        # path for static files
        location  /static {
            alias /path/to/static;
            autoindex on;
            expires max;
        }

        location / {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;

            if (!-f $request_filename) {
                proxy_pass http://flask_server;
                break;
            }
        }
    }

}

关于python - 使用 nginx 和 gunicorn 运行 flask 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13660118/

相关文章:

node.js - Nginx proxy_pass 在端口 80 上不起作用

nginx - flask 、Gunicorn、NGINX、Docker : What is properly the way to config SERVER_NAME and proxy_pass?

javascript - 根据按下的字段使用 Jinja2 和 Flask 对对象列表进行排序

python - 在 virtualenv 中无法 "import matplotlib.pyplot as plt"

python - 我需要找到一种方法让我的代码有时间加载页面,然后才获取 HTML 代码

nginx - 在 nginx 提供的 HTML 文件中包含主机名

python - 如何创建传递自定义半径的地理热图

Nginx Plus 不流式传输 HLS

python - 将 Python 翻译成 C

python - 我需要根据两列数据帧生成新列,如何才能更快?