我'm still pretty new with Flask/Nginx/Gunicorn as this is only my second site using the combination. I created a website based off of Miguel Grinberg' s tutorial所以我的文件结构与本教程完全相同 .
在我以前的Flask应用程序中,我的应用程序位于一个名为 app.py
的文件中,因此当我使用Gunicorn时我刚刚调用gunicorn app:app
既然我的新应用程序被拆分成多个文件,我使用了一个文件 run.py
来启动应用程序,但是我已经阅读了其他问题和教程但是它们没有用 . 当我运行 gunicorn run:app
并尝试访问该站点时,我收到502 Bad Gateway错误 .
我认为我的问题是比Nginx或Flask更多的Gunicorn,因为如果我输入 ./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;
}
}
1 回答
发生的事情是当gunicorn导入
app.py
时开发服务器正在运行 . 您只希望在直接执行文件时发生这种情况(例如,python app.py
) .完成此更改后,您应该能够使用
gunicorn run:app
运行该应用程序 . 请注意,gunicorn默认使用端口8000 . 如果您希望在备用端口(例如,8001)上运行,则需要使用gunicorn -b :8001 run:app
指定 .