Django with ASGI
How to setup and use Django with ASGI
Make sure that you have a asgi.py file in your django project directory with content similar to this.
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
application = get_asgi_application()
Install gunicorn, uvicorn and uvicorn_worker.
pip install gunicorn uvicorn[standard] uvicorn_worker
Add to the settings.py file
ASGI_APPLICATION = 'project.asgi.application'
Create systemd socket and service files for Gunicorn
sudo nano /etc/systemd/system/gunicorn.socket
[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
[Install]
WantedBy=sockets.target
sudo nano /etc/systemd/system/gunicorn.service
[Unit]
Description=Gunicorn ASGI service for Django
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/path/to/project
ExecStart=path/to/project/venv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
-k uvicorn_worker.UvicornWorker \
project.asgi:application
[Install]
WantedBy=multi-user.target
Configure Nginx to proxy pass to Gunicorn
sudo nano /etc/nginx/sites-available/your-domain
server {
listen 80;
...
location / {
proxy_pass http://unix:/run/gunicorn.sock;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Port $server_port;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
Add to the settings.py file
sudo nano path/to/project/settings.py
USE_X_FORWARDED_PORT = True
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
Reload the necessary services
sudo systemctl daemon-reload
sudo systemctl restart gunicorn.service gunicorn.socket
sudo systemctl restart nginx