Setting up uWSGI

Published on December 29, 2020

Installation

Install uWSGI:

apk add python3 py3-pip py3-virtualenv uwsgi uwsgi-python3

Configuration

Start the service:

/etc/init.d/uwsgi start
rc-update add uwsgi

Per-Application Setup

Add a user for the Python application:

useradd -m flask

Log in as the user:

su flask
cd ~

Create the virtual environment for the application:

virtualenv env

Activate the virtual environment:

source env/bin/activate

Install Flask;

pip install flask

Edit ~/app.py:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

Deactivate the virtual environment:

deactivate

Press Ctrl+D or type exit to log out of the flask user.

To test our uWSGI installation, we can first run uwsgi from the command line:

uwsgi --socket 127.0.0.1:5000 --protocol=http --plugins python --uid flask --chdir /home/flask --virtualenv /home/flask/env -w app:app

Forward the port using SSH:

ssh -L 5000:localhost:5000 example.com

Point your browser to http://localhost:5000 to test the Python application.

uWSGI Emperor

Create a directory for the uWSGI application sockets:

mkdir /var/run/uwsgi-apps
chown -hR uwsgi: /var/run/uwsgi-apps

Edit /etc/uwsgi/conf.d/flask:

[uwsgi]
uid = flask
gid = flask
chown-socket = nginx
socket = /var/run/uwsgi-apps/flask.sock
chdir = /home/flask/app
virtualenv = /home/flask/app
module = app:app
plugin = python

Correct the permissions for /etc/uwsgi:

chown -R uwsgi: /etc/uwsgi

Reload uWSGI emperor:

/etc/init.d/uwsgi reload

Nginx

If you want to add the application to a subdirectory, edit your configuration as follows:

	location /flask {
		try_files $uri @flask;
	}

	location @flask {
		rewrite /foo/(.*)$ /$1 break;
		include uwsgi_params;
		uwsgi_pass unix:/var/run/uwsgi-apps/flask.sock;
	}

Otherwise, you can also host your application as part of a (sub)domain:

	location / {
		try_files $uri @flask;
	}

	location @flask {
		include uwsgi_params;
		uwsgi_pass unix:/var/run/uwsgi-apps/flask.sock;
	}


If you like my work or if my work has been useful to you in any way, then feel free to donate me a cup of coffee. Any donation is much appreciated!