Report this

What is the reason for this report?

Django-channels with supervisor, nginx and daphne not activating web sockets. How to configure them.

Posted on October 31, 2018

The Nginx configuration file:

upstream app_server {
    server unix:/home/urban/run/gunicorn.sock fail_timeout=0;
}
upstream channels-backend {
    server unix:/home/urban/run/daphne.sock;
}
server {

    # add here the ip address of your server
    # or a domain pointing to that ip (like example.com or www.example.com)
    server_name hometadka.com www.hometadka.com 206.189.130.189;

    keepalive_timeout 5;
    client_max_body_size 4G;

    access_log /home/urban/logs/nginx-access.log;
    error_log /home/urban/logs/nginx-error.log;

    location /static/ {
        alias /home/urban/homet_dj/static/;
    }

    # checks for static file, if not found proxy to app
    location / {
        try_files $uri @proxy_to_app;
    }

location /ws/ {
        try_files $uri @proxy_to_ws;
    }

location @proxy_to_ws {
       proxy_pass http://channels-backend;

        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;
}

Supervisor file:

[program:homet_dj]
command=/home/urban/bin/gunicorn_start
user=urban
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/home/urban/logs/gunicorn-error.log

[program:server_workers]
command=/home/urban/bin/python /home/urban/homet_dj/www/manage.py runworker
directory=/home/urban/homet_dj/
user=web
autostart=true
autorestart=true
redirect_stderr=true
stopasgroup=true

[program:server_interface]
command=/home/urban/bin/daphne -b 127.0.0.1 -p 8000 yourapp.asgi:channel_layer
directory=/home/urban/homet_dj/
autostart=true
autorestart=true
stopasgroup=true
user=web
stdout_logfile = /home/urban/logs/gunicorn-error.log

The settings.py file:

ASGI_APPLICATION = "homet_dj.routing.application"

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

The routing.py file:

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter

from notify.routing import notification_urlpatterns

application = ProtocolTypeRouter({
    "websocket": AuthMiddlewareStack(
            URLRouter(notification_urlpatterns),
        ),
})

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.