Skip to content

Instantly share code, notes, and snippets.

@edelans
Forked from mcescalante/instructions.md
Created June 11, 2016 22:28
Show Gist options
  • Save edelans/8661bdf2146284448689d150d8da5df0 to your computer and use it in GitHub Desktop.
Save edelans/8661bdf2146284448689d150d8da5df0 to your computer and use it in GitHub Desktop.
Run a Flask application with gunicorn and nginx

This guide assumes:

  • You have a VPS (something like DigitalOcean, Linode, etc.)
  • You have a Flask application and a basic understanding of command line instructions
  • You've got nginx installed and know where your configuration files are

Instructions

  1. First, you should install gunicorn on your box or virtualenv with pip:
  • source venv/bin/activate (optional, if you're not using virtualenv)
  • pip install gunicorn
  1. Add a configuration block to your nginx configuration:

Note: change 127.0.0.1:5000 to the port that your flask application is set to run on.

server {
  listen 80;
  server_name example.com;
  
  keepalive_timeout 5;
  
  location / {
    proxy_pass http://127.0.0.1:5000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

}
  1. Make locations for the gunicorn logs, and start your application:

Note: change 127.0.0.1:5000 to the correct port, and change app:app if you've got a different name

  • mkdir /var/log/gunicorn/
  • gunicorn --access-logfile /var/log/gunicorn/access_log --error-logfile /var/log/gunicorn/error_log --pythonpath /var/www/yourapppath -b 127.0.0.1:5000 app:app
  1. Restart nginx nginx -s reload
  2. Done. Your flask application should be running on the domain you set in the nginx configuration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment