Skip to content

Instantly share code, notes, and snippets.

@mcescalante
Last active July 25, 2023 14:07
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mcescalante/5db616b9a826605f1df35f79b09cf6f6 to your computer and use it in GitHub Desktop.
Save mcescalante/5db616b9a826605f1df35f79b09cf6f6 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. Restart nginx nginx -s reload

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

Note: change 127.0.0.1:5000 to match your nginx block if you used a different 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. Done. Your flask application should be running on the domain you set in the nginx configuration

Notes

  • Don't forget to run this with screen or supervisord or some other init daemon so that the application doesn't shut down when you exit the shell. Yes, adding & at the end will keep it running, but it's the least elegant way
  • sudo killall -HUP gunicorn gracefully restarts workers if you change any of your python code and want to restart the application
  • Feel free to comment with questions or anything else and I can expand on it :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment