Serve Python Flask web app with NGINX

I’m running this on Ubuntu environment. If you understand how below things work then you may applied it on other distros

Let say you have Flask app something like this

# main.py

from flask import Flask

app = Flask(__name__)


@app.route('/')
def index():
    return '''
        <html>
            <body>
                <center><strong>Hello, I'm from Flask application</strong></center>
            </body>
        </html>
    '''


if __name__ == '__main__':
    app.run()

And then I’m gonna include gunicorn in my python environment. gunicorn is used to manage python process for your web app. I’m using pip to manage python library, so I’m gonna include in requirements.txt and pip install -r requirements.txt

# requirements.txt
Flask==1.1.1
gunicorn==20.0.4

After that, I’m gonna write some service file to manage our python process. I put the service file in /etc/systemd/system/python-test.service

[Unit]
Description=Run my Flask web app
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/path/to/your/python
Environment="PATH=/path/to/your/python/venv/bin"
ExecStart=/path/to/your/python/venv/bin/gunicorn --workers 2 --bind unix:/var/www/python/python-test.sock -m 007 main:app

[Install]
WantedBy=multi-user.target

Finally, my NGINX config

server {
        listen 80;
        server_name python.test;

        location / {
                include proxy_params;
                proxy_pass http://unix:/var/www/python/python-test.sock;
        }

        location ~ /\.ht {
                deny all;
        }
}

You are done! You may run systemctl daemon-reload, service python-test restart and service nginx restart for your system to reload the configuration you save just now.

comments powered by Disqus