This is a cut-down version of our projects done for clients.
This post & demo is just to showcases the basic part of the deployment.
We have left-out the actual client specific details for the obvious reasons.
Also this cut-down version assumes - django, gunicorn & nginx - all runs on the same linux server. Else you might have to use TCP instead of socket file.
The main parts of such deployments are -
Gunicorn communicates with Nginx using a Unix socket instead of a port.
This improves security and performance by avoiding unnecessary network overhead. The socket file (e.g., /run/gunicorn.sock
) acts as a bridge between Gunicorn (Python app server) and Nginx (web server).
Gunicorn systemd service allows Django to run automatically in the background.
It starts Gunicorn, sets the working directory, runs multiple workers for better performance, and binds the app to a socket.
This ensures Django runs as a daemon and restarts on failure.
e.g. systemd service /etc/systemd/system/gunicorn.service
:
[Service]
User=django
Group=www-data
WorkingDirectory=/home/user/myproject
ExecStart=/usr/bin/gunicorn
--workers 3
--bind unix:/run/gunicorn.sock
myproject.wsgi:application
Nginx acts as a reverse proxy for Gunicorn, handling client requests, serving static files, and improving security.
Instead of exposing Django directly, Nginx forwards requests via the Gunicorn socket, ensuring better scalability and load balancing.
Example Nginx config:
server {
listen 80;
server_name example.com;
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}
The WSGI (Web Server Gateway Interface) is a Python standard that allows web servers (like Gunicorn) to communicate with Django.
It acts as the entry point for the application when deployed.
How WSGI Works in Deployment
e.g. wsgi.py
in Django-project/wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sdtech.settings')
application = get_wsgi_application()