Search code examples
djangodockernginxdjango-channelsdaphne

Deploy django channels to dcoker and use nginx has a proxy server


Im trying to deploy django channels using docker, and im using the daphne protocol to serve the application. when i run that its starts successfully but i'm unable to connect with the websocket.

i can connect with the application in other routes but cannot connect with the websocket

the websocket is served in HTTPS://EXAMPLE.COM/WS/SOCK

this is my asgi.py

 application = ProtocolTypeRouter({
'http': django_asgi_app,
'websocket': AllowedHostsOriginValidator(
    AuthMiddlewareStack(
        URLRouter(websocket_urlpatterns)
    ))})

Dockerfile

FROM python:3.8
ENV PYTHONUNBUFFERED 1
WORKDIR /myproject
ADD . /myroject
RUN pip install -r /myprjoect/requirements.txt
EXPOSE 8000
CMD ["daphne", "-b", "0.0.0.0", "-p", "8000", "myproject.asgi:application"]

nginx.conf

 location / {
            proxy_set_header Host $http_host;
            proxy_set_header X-Forward-Proto https;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://localhost:8443/;
    }

    #path to proxy my WebSocket requests

    location /ws/ {
            proxy_pass http://localhost:8443;
            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;         
    }

and im using the docker-compose to up the application anf its configuration is

version: "3.8"
services:
  myservice:
    image: myimage
    container_name: my_container
    ports:
      - 8443:8000

Solution

  • Now my websocket is woking fine. To resolve this problem i had to change proxy_set_header Connection “upgrade”; to proxy_set_header Connection Upgrade;