You’ve just written a great Python web application. Now, you want to share it with the world. In order to do that, you need a server, and some software to do that for you.
The following is a comprehensive guide on how to accomplish that, on multiple Linux-based operating systems, using nginx and uWSGI Emperor. It doesn’t force you to use any specific web framework — Flask, Django, Pyramid, Bottle will all work. Written for Ubuntu, Debian, Fedora, CentOS 7 and Arch Linux (should be helpful for other systems, too). Now with an Ansible Playbook.
Revision 7c (2020-05-01): works with Ubuntu 20.04 and Fedora 32; previous Revision 7a (2020-02-03): Move virtual environment to separate venv folder to improve Python upgrades (venvs should be ephemeral); add Docker section
CI status for the associated Ansible Playbook:
In order to deploy your web application, you need a server that gives you root and ssh access — in other words, a VPS (or a dedicated server, or a datacenter lease…). If you’re looking for a great VPS service for a low price, I recommend Hetzner Cloud (reflink 1), which offers a pretty good entry-level VPS for €2.49 + VAT / month (with higher plans available for equally good prices). If you want to play along at home, without buying a VPS, you can create a virtual machine on your own, or use Vagrant with a Vagrant box for Fedora 32 (
Your server should also run a modern Linux-based operating system. This guide was written and tested on:
Ubuntu 16.04 LTS, 18.04 LTS, 20.04 LTS or newer
Debian 9 (stretch), 10 (buster) or newer
Fedora 29-32 or newer (with SELinux enabled and disabled)
CentOS 7 (with SELinux enabled and disabled) — manual guide should also work on RHEL 7. CentOS 8 does not have uWSGI packages in EPEL as of May 2020, but they should become available soon.
Debian 8 (jessie), and Fedora 24 through 28 are not officially supported, even though they still probably work.
What if you’re using Docker? The story is a bit complicated, and this guide does not apply, but do check the Can I use Docker? at the end of this post for some hints on how to approach it.
Users of other Linux distributions (and perhaps other Unix flavors) can also follow this tutorial. This guide assumes
systemd as your init system; if you are not using systemd, you will have to get your own daemon files somewhere else. In places where the instructions are split three-way, try coming up with your own, reading documentation and config files; the Arch Linux instructions are probably the closest to upstream (but not always). Unfortunately, all Linux distributions have their own ideas when it comes to running and managing nginx and uWSGI.
nginx and uWSGI are considered best practices by most people. nginx is a fast, modern web server, with uWSGI support built in (without resorting to reverse proxying). uWSGI is similarly aimed at speed. The Emperor mode of uWSGI is recommended for init system integration by the uWSGI team, and it’s especially useful for multi-app deployments. (This guide is opinionated.)
A Playbook that automates everything in this tutorial is available.
Install Ansible on your control computer (not necessarily the destination server).
Clone the Playbook from GitHub.
README.md. You should also understand how Ansible works.
Configure (change three files:
Make sure all the dependencies are installed on your destination server
ansible-playbook -v nginx-uwsgi.yml -i hostsand watch magic happen.
Skip over to End result and test your site.
Even though I personally recommend the Playbook as a much less error-prone way to set up your app, it might not be compatible with everyone’s system, or otherwise be the wrong solution. The original manual configuration guide is still maintained.
Even if you are using the Playbook, you should still read this to find out what happens under the hood, and to find out about other caveats/required configuration changes.
All the commands in this tutorial are meant to be run as root — run
sudo su first to get an administrative shell. This tutorial assumes familiarity with basic Linux administration and command-line usage.
Start by installing Python 3 (with venv), nginx and uWSGI. I recommend using your operating system’s packages. Make sure you are downloading the latest versions available for your OS (update the package cache first). For uWSGI, we need the
python3 plugins. (Arch Linux names the
logfile plugin may be built-in — check with your system repositories!). I’ll also install Git to clone the tutorial app, but it’s optional if your workflow does not involve Git.
yum install epel-release yum install python36 uwsgi uwsgi-plugin-python36 uwsgi-logger-file nginx git wget
This tutorial will work for any web framework. I will use a really basic Flask app that has just one route (
/), a static
hello.png file and a
favicon.ico for demonstration purposes. The app is pretty basic, but all the usual advanced features (templates, user logins, database access, etc.) would work without any other web server-related config. Note that the app does not use
app.run(). While you could add it, it would be used for local development and debugging only, and would have to be prepended by
if __name__ == '__main__': (if it wasn’t, that server would run instead of uWSGI, which is bad)
The app will be installed somewhere under the
/srv directory, which is a great place to store things like this. I’ll choose
/srv/myapp for this tutorial, but for real deployments, you should use something more distinguishable — the domain name is a great idea.
If you don’t use Flask, this tutorial also has instructions for other web frameworks (Django, Pyramid, Bottle) in the configuration files; it should be adjustable to any other WSGI-compliant framework/script nevertheless.
We’ll start by creating a virtual environment, which is very easy with Python 3:
--prompt option is not supported on some old versions of Python, but you can just skip it if that’s the case, it’s just to make the prompt after
source bin/activate more informative.)
Now, we need to put our app there and install requirements. An example for the tutorial demo app:
cd /srv/myapp git clone https://github.com/Kwpolska/flask-demo-app appdata venv/bin/pip install -r appdata/requirements.txt
I’m storing my application data in the
appdata subdirectory so that it doesn’t clutter the virtual environment (or vice versa). You may also install the
uwsgi package in the virtual environment, but it’s optional.
What this directory should be depends on your web framework. For example, for a Django app, you should have an
appdata/manage.py file (in other words,
appdata is where your app structure starts). I also assumed that the
appdata folder should have a
static subdirectory with all static files, including
favicon.ico if you have one (we will add support for both in nginx).
At this point, you should chown this directory to the user and group your server is going to run as. This is especially important if uwsgi and nginx run as different users (as they do on Fedora). Run one of the following commands:
Parts of the configuration depend on your operating system. I tried to provide advice for Ubuntu, Debian, Fedora, CentOS and Arch Linux. If you experience any issues, in particular with plugins, please consult the documentation.
We need to write a configuration file for uWSGI and nginx.
Start with this, but read the notes below and change the values accordingly:
Save this file as:
/etc/uwsgi/vassals/myapp.ini(create the directory first and chown it to http:
mkdir -p /etc/uwsgi/vassals; chown -R http:http /etc/uwsgi/vassals)
The options are:
socket— the socket file that will be used by your application. It’s usually a file path (Unix domain socket). You could use a local TCP socket, but it’s not recommended.
chdir— the app directory.
binary-path— the uWSGI executable to use. Remove if you didn’t install the (optional)
uwsgipackage in your virtual environment.
virtualenv— the virtual environment for your application.
module— the name of the module that houses your application, and the object that speaks the WSGI interface, separated by colons. This depends on your web framework:
Framework Flask, Bottle Django Pyramid Package module where
projectis the package with
app = bottle.default_app()
app = config.make_wsgi_app()
Caveats Make sure
appis not in an
if __name__ == '__main__':block
Add environment variable for settings:
env = DJANGO_SETTINGS_MODULE=project.settings
appis not in an
if __name__ == '__main__':block (the demo quickstart does that!)
gid— the names of the user account to use for your server. Use the same values as in the
threads— control the resources devoted to this application. Because this is a simple hello app, I used one process with one thread, but for a real app, you will probably need more (you need to see what works the best; there is no algorithm to decide). Also, remember that if you use multiple processes, they don’t share memory (you need a database to share data between them).
plugins— the list of uWSGI plugins to use. For Arch Linux, use
plugins = python(the
logfileplugin is always active). For CentOS, use
plugins = python36.
logger— the path to your app-specific logfile. (Other logging facilities are available, but this one is the easiest, especially for multiple applications on the same server)
env— environment variables to pass to your app. Useful for configuration, may be specified multiple times. Example for Django:
env = DJANGO_SETTINGS_MODULE=project.settings
You can test your configuration by running
uwsgi --ini /path/to/myapp.ini (disable the logger for stderr output or run
tail -f /srv/myapp/uwsgi.log in another window).
If you’re using Fedora or CentOS, there are two configuration changes you need to make globally: in
/etc/uwsgi.ini, disable the
emperor-tyrant option (which we don’t need, as it sets uid/gid for every process based on the owner of the related
.ini config file — we use one global setup) and set
gid = nginx. We’ll need this so that nginx can talk to your socket.
We need to configure our web server. Here’s a basic configuration that will get us started:
Save this file as:
Arch Linux: add
include /etc/nginx/conf.d/*.conf;to your
Note that this file is a very basic and rudimentary configuration. This configuration is fine for local testing, but for a real deployment, you will need to adjust it:
server_nameto your real domain name
you might also want to add custom error pages, log files, or change anything else that relates to your web server — consult other nginx guides for details
nginx usually has some server already enabled by default — edit
/etc/nginx/nginx.confor remove their configuration files from your sites directory to disable it
After you’ve configured uWSGI and nginx, you need to enable and start the system services.
All you need is:
Verify the service is running with
systemctl status emperor.uwsgi
Make sure you followed the extra note about editing
/etc/uwsgi.ini earlier and run:
Verify the service is running with
systemctl status uwsgi
If you disabled SELinux, this is enough to get an app working and you can skip over to the next section.
If you want to use SELinux, you need to do the following to allow nginx to read static files:
Hopefully, this is enough (you can delete the file). In case it isn’t, please read SELinux documentation, check audit logs, and look into
Ubuntu and Debian (still!) use LSB services for uWSGI. Because LSB services are awful, we’re going to set up our own systemd-based (native) service.
Start by disabling the LSB service that comes with Ubuntu and Debian:
.service file from the uWSGI systemd documentation to
/etc/systemd/system/emperor.uwsgi.service. Change the ExecStart line to:
You can now reload systemd daemons and enable the services:
systemctl daemon-reload systemctl enable nginx emperor.uwsgi systemctl reload nginx systemctl start emperor.uwsgi
Verify the service is running with
systemctl status emperor.uwsgi. (Ignore
the warning about no request plugin)
Your web service should now be running at http://localhost/ (or wherever you set up server to listen).
If you used the demo application, you should see something like this (complete with the favicon and image greeting):
If you want to test with cURL:
curl -v http://localhost/ curl -I http://localhost/favicon.ico curl -I http://localhost/static/hello.png
Hopefully, everything works. If it doesn’t:
Check your nginx, system (
systemctl status SERVICE) and uwsgi (
Make sure you followed all instructions.
If you get a default site, disable that site in nginx config (
/etc/nginx/nginx.confor your sites directory).
If you have a firewall installed, make sure to open the ports your web server runs on (typically 80/443). For
If it still does not work, feel free to ask in the comments, mentioning your distribution, installation method, and what doesn’t work.
This blog post is written for systems running standalone. But Docker is a bit special, in that it offers a limited subset of OS features this workflow expects. The main issue is with user accounts, which generally work weird in Docker, and I had issues with
setgid as used by uWSGI. Another issue is the lack of systemd, which means that another part of the tutorial fails to apply.
This tutorial uses uWSGI Emperor, which can run multiple sites at once, and offers other management features (such as seamless code restarts with
touch /etc/uwsgi/vassals/myapp.ini) that may not be useful or easy to use in a Docker environment. You’d probably also run uWSGI and nginx in separate containers in a typical Docker deployment.
Regardless, many parts of this tutorial can be used with Docker, although with the aforementioned adjustments. I have done some work on this topic. This tutorial has an Ansible Playbook attached, and the tutorial/playbook are compatible with five Linux distros in multiple versions. How do I know that there were no unexpected bugs in an older version? I could grab a Vagrant image or set up a VM. I do that when I need specific testing, but doing it for each of the distros on each update would take at least half an hour, probably even more. Yeah, that needs automating. I decided to use GitHub Actions for the CI, which can run anything, as long as you provide a Dockerfile.
The Docker images were designed to support running the Playbook and testing it. But the changes, setups and patches could be a good starting point if you wanted to make your own Docker containers that could run in production. You can take a look at the Docker files for CI The images support all 5 distros using their base images, but you could probably use Alpine images, or the
python docker images; be careful not to mix Python versions in the latter case.
That said, I still prefer to run without Docker, directly on the system. Less resources wasted and less indirection. Which is why this guide does it the traditional way.
This reflink gives you €20 in credit (expires the next month). I earn €10 after you spend €10 of your own.