Deploy Django Channels with Nginx and Uvicorn

Ashin Shakya
2 min readMar 10, 2024

--

Implement django channels with nginx, uvicorn

If you have ever used django channels, then you must have used daphne to build your django applications. It is not necessary to use daphne but what if we could use other services as well. There are lots of asgi services like daphne such as Uvicorn and Hypercorn over which we can deploy our application.

I am assuming you already have implemented a basic setup of django channels. If not follow this https://channels.readthedocs.io/en/latest/ doc and create a simple django channels application to get started.

Once you have setup your django channel we will now use uvicorn to run the django server. We have all used gunicorn over production for http and https:// connection requests right but it does not work for websockets which require asyn servers. So yes, uvicorn is an asgi server while gunicorn is wsgi server.

So let’s start by removing and installing some required libraries. You may remove the daphne from your INSTALLED_APPS and uninstall the library as well since we will not be needing that. Instead install using the following libraries.

pip install uvicorn
pip install websockets

Once you have installed these, you can now run your django application locally and in production as well using the following command

uvicorn proj.asgi:application

Now, if you want to run for development add a reloadand mention host and port if you have to specify it and go ahead with the following command

uvicorn proj.asgi:application --reload --host 0.0.0.0 --port 8000

Further, if you want to use it for production along with gunicorn you will need to mention the asgi:application and uvicorn.workers.UvicornWorker .

gunicorn proj.asgi:application -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000 --workers 4 --threads 2 --log-level info

Now, we will also require to configure our nginx as well to enable ws and wss protocol connection requests. So, let’s configure our nginx.conf as well.

upstream mydomain {
...
}

server {
listen 80;
listen 443 ssl;

...

location / {
proxy_pass http://mydomain;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}

location /ws/ {
proxy_pass http://mydomain;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
}

....
}

You can check your nginx configuration and reload your nginx service.

nginx -t

systemctl restart nginx

Now, check your application and try to open the page. It will work. If it does not work, try checking your connection over a secure channel by replacing ws with wss which is similar to http and https .

Yeah! That’s it. Thanks for reading. I hope you deployed your application.

--

--