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 https://tms.regency1153.com.

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

[Unit]
Description=TMS Web Application
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
User=ubuntu
Environment=DJANGO_SETTINGS_MODULE=tms.settings_prd
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 {
    server_name tms.regency1153.com;

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

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

    location / {
        include proxy_params;
        proxy_pass http://127.0.0.1:8000;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/tms.regency1153.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/tms.regency1153.com/privkey.pem; # 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 = tms.regency1153.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot




    listen 80;
    server_name tms.regency1153.com;
    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.