Deploy Django applications with nginx and systemd

In this post I will explain how I deploy Django applications using Systemd and Nginx, in this case I will show I host the Django website

Systemd is a software that comes with most Linux distros and can be used to create services. A service in the context of systemd is simply a managed background process, the service is defined in a file with the extension .service inside the folder /etc/systemd/system.

After defining the service it is possible to start, stop and restart with systemctl command:

systemctl status service_name
systemctl start service_name
systemctl stop service_name
systemctl restart service_name

To define the Django application as a service create the following file /etc/systemd/service/service_name.service

Description=TMS Web Application
ExecStart=/home/ubuntu/.local/bin/gunicorn tms.wsgi --preload --workers=4 --timeout 300

The Environment= entry in the file is optional, this entry defines environment variables to be loaded on the start of the service. In this case this is useful to me since I create an environment file for production and use the environment variable DJANGO_SETTINGS_MODULE to load it.

The command /home/ubuntu/.local/bin/gunicorn tms.wsgi --preload --workers=4 --timeout 300 will start the web server at port 8000, and the nginx will then proxy the web requests to this port:

server {

    location /static/ {
        root /var/www/;

    location /media/ {
        root /var/www/;

    location / {
        include proxy_params;

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

server {
    if ($host = {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    return 404; # managed by Certbot


There are more software involved to host the aplication as for example gunicorn to start the Django application and certbot to manage https certificates.