Create daphne asgi + websocket | Django | ubuntu 20.04

!important is to first install redis server

sudo apt install redis

Create daphne ASGI

must allow whatever port you set

sudo ufw allow [port]

1.Install daphne and channels_redis in python env

pip install daphne channels_redis

2.create systemd service
sudo nano /etc/systemd/system/daphne_subdomain1.service
[Unit]
Description=WebSocket Daphne Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/home/myuser/django/subdomain1
ExecStart=/home/myuser/django/subdomain1/bin/python /home/myuser/django/subdomain1/bin/daphne -e ssl:9002:privateKey=/etc/letsencrypt/live/subdomain1/privkey.pem:certKey=/etc/letsencrypt/live/subdomain1/fullchain.pem myapp.asgi:application
Restart=on-failure

[Install]
WantedBy=multi-user.target
3.Start, Enable and check status of new created daphne service.
sudo systemctl start daphne_subdomain1.service && sudo systemctl enable daphne_subdomain1.service && sudo systemctl status daphne_subdomain1.service

4.Update subdomain1 nginx config.

sudo nano /etc/nginx/sites-available/subdomain1
upstream websocket{
	server 127.0.0.1:6379;
}
server {
    server_name subdomain1.myapp.com;
    location = /favicon.ico { access_log off; log_not_found off; }
    location /static {
        root /home/myuser/django/subdomain1;
    }
    location /files {
        root /home/myuser/django/subdomain1;
    }      
	location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/run/gunicorn_subdomain1.sock;
    }
    
    location /ws {
        proxy_pass http://websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_redirect off;
        proxy_set_header Host $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-Host $server_name;
        proxy_set_header X-Forwarded-Proto  $scheme;
    }
}

Restart nginx service

sudo nginx -t && sudo systemctl restart nginx

base on https://channels.readthedocs.io/en/latest/tutorial/part_3.html

5.In your django asgi.py
import os
import django

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import myapp.routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')

django.setup()

application = ProtocolTypeRouter({
    "websocket": AuthMiddlewareStack(
        URLRouter(
            myapp.routing.websocket_urlpatterns
        )
    ),
})

6.Add this to your django settings.py

# Channels
ASGI_APPLICATION = 'myapp.asgi.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

To start the daphne service when reboot must add another service for that. Create sh script in /root/daphne_subdomain1_boot.sh

#!/bin/sh
sudo systemctl start daphne_subdomain1.service
Make the sh script executable.
sudo chmod u+x /root/daphne_subdomain1_boot.sh
after that need to create new service for daphne_subdomain1_boot.sh to run. Create new service /etc/systemd/system/daphne_subodmain1_boot.service
[Service]
ExecStart=/root/daphne_subdomain1_boot.sh

[Install]
WantedBy=default.target

after creating the new boot service for daphne subdomain1. Start and enable the new daphne_subodmain1_boot.service
sudo systemctl start daphne_subodmain1_boot.service && sudo systemctl enable daphne_subodmain1_boot.service

Add new comment