Deploy Flask on Nginx w/uWSGI

Written by Flask, Python, Servers

Required: Updated Debian 10 server with root privileges and a domain name.

Install Nginx

apt install nginx

Verify Nginx is running by navigating to the server’s IP address.

Install Flask & uWSGI

apt install python3-pip python-dev
pip3 install uwsgi flask

Create Web Directory

mkdir /var/www/[project_name]

Create Simple App

nano /var/www/[project_name]/main.py

Add the following:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def index():
    return "Hello World!"

if __name__ == "__main__":
    app.run(host="0.0.0.0")

Create config-uwsgi.ini

nano /var/www/[project_name]/config-uwsgi.ini

Add the following:

[uwsgi]

app = main
module = %(app)
callable = app

socket = /var/www/[project_name]/[project_name].sock
chdir = /var/www/[project_name]
chmod-socket = 666

processes = 4
die-on-term = true

Setup Nginx

Remove default configuration

rm /etc/nginx/sites-enabled/default

Create new configuration

nano /var/www/[project_name]/config-nginx.conf

Add the following:

server {
    listen 80;
    listen [::]:80;

    server_name [your_domain].com www.[your_domain].com;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/var/www/[project_name]/[project_name].sock;
    }
}

Create symoblic link from Nginx directory to conf.d directory

ln -s /var/www/[project_name]/config-nginx.conf /etc/nginx/conf.d/

Restart Nginx

systemctl restart nginx

Run uWSGI

Start service

nohup uwsgi /var/www/[project_name]/config-uwsgi.ini &

Notes:

CTRL + C to hide the process. Run uWSGI under systemd for live project.

Install Let’s Encrypt SSL Certificate

Install Certbot

apt install certbot python-certbot-nginx

Requests certificate

certbot --nginx

Follow the Certbot prompts.

Notes:

Redirecting HTTP traffic to HTTPS is recommended.

Talk soon,
Shane Bellone