Reputation: 1653
I'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 so my file structure is exactly the same as in this tutorial.
In my previous Flask app, my app was in a single file called app.py
so when I used Gunicorn I just called
gunicorn app:app
Now that my new application is split into multiple files I used a file run.py
to start the app, but I'm not sure how I should call Gunicorn now. I've read other questions and tutorials but they haven't worked. When I run gunicorn run:app
and I try to access the site I get a 502 Bad Gateway error.
I think my problem is more Gunicorn than Nginx or Flask, since the site works if I just type ./run.py
. In any case, I've included my Nginx config and a few other files below. Thanks so much for your help!
File: 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)
File: 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)
File: 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;
}
}
Upvotes: 3
Views: 3630
Reputation: 20709
What is happening is the development server is running when gunicorn imports app.py
. You only want that to happen when the file is executed directly (e.g., 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)
Once you've made this change, you should be able to run the application with gunicorn run:app
. Note that gunicorn uses port 8000 by default. If you wish to run on an alternate port (e.g., 8001), you'll need to specify that with gunicorn -b :8001 run:app
.
Upvotes: 2