Simple web stack with flask nginx gunicorn supervisor

A simple web stack using flask, nginx, gunicorn and supervisor in python with minimum configuration. This is useful if you want to QUICKLY setup a simple but production ready web service.

Create web app

# simpleapp.py
from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/")
def index():
    return jsonify({
        "message": "Hello, World!"
    }), 200

Install dependencies

# install system packages
$ sudo apt-get install nginx
$ sudo apt-get install gunicorn
$ sudo apt-get install supervisor
[optional] $ sudo apt-get install logrotate
# install python library
$ sudo pip install flask

Configuration for nginx

# simpleapp-nginx
# copy the config to: /etc/nginx/sites-enabled
# or create link: $ ln -s /path/to/simpleapp-nginx /etc/nginx/sites-enabled
server {
  listen 80;

  location / {
    include proxy_params;
    proxy_pass http://unix:/run/gunicorn/socket;
  }
}

Configuration for supervisor

# simpleapp-supervisor.conf
# copy the config to: /etc/supervisor/conf.d
# or create link: $ ln -s /path/to/simpleapp-supervisor.conf /etc/supervisor/conf.d
[program:gunicorn]
command=gunicorn --workers 4 \
  --bind unix:/run/gunicorn/socket \
  --access-logfile /var/log/gunicorn/access.log \
  --log-file /var/log/gunicorn/app.log \
  --capture-output simpleapp:app
directory=/path/to/project
user=root
autostart=true
autorestart=true
redirect_stderr=true

[Optional] Configuration for logrotate

# simpleapp-logrotate
# copy the config to /etc/logrotate.d
# or create link: $ ln -s /path/to/simpleapp-logrotate /etc/logrotate.d
/var/log/gunicorn/*.log {
    compress
    delaycompress
    missingok
    notifempty
    weekly
}

Start service

$ /etc/init.d/nginx start
$ /etc/init.d/supervisor start

References

Notes

  • The above web stack is deployed with a regular ubuntu linux, but a docker container is also recommended
  • The above web stack is deployed with system python, but a python venv is highly recommended

flask nginx gunicorn supervisor