I recently built a Django application using Django Channels for WebSocket support. My asgi.py is set up for handling both HTTP and WebSocket connections, and everything works perfectly in development using Daphne and Uvicorn.
In Productin initially, my app was running on Gunicorn (WSGI), but since I need WebSocket support, I switched to Uvicorn (ASGI). To achieve this, I modified my gunicorn.service file to use UvicornWorker instead of the default WSGI worker.
I encountered the error:
Django can only handle ASGI/HTTP connections, not lifespan.
To fix this, I created a custom worker class based on a solution from older Stack Overflow answers:
from uvicorn.workers import UvicornWorker
class MyUvicornWorker(UvicornWorker):
CONFIG_KWARGS = {"lifespan": "off"}
Then, I updated my gunicorn.service file:
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=django
Group=www-data
WorkingDirectory=/home/django/my_project
ExecStart=/home/django/my_project/venv/bin/gunicorn \
--limit-request-line 8190 \
--access-logfile /var/log/gunicorn/access.log \
--error-logfile /var/log/gunicorn/error.log \
-k project.uvicorn_worker.MyUvicornWorker \
--workers 3 \
--env DJANGO_SETTINGS_MODULE=project.settings.base \
--bind unix:/run/gunicorn.sock \
--log-level=debug \
project.asgi:application
ExecReload=/bin/kill -HUP $MAINPID
[Install]
WantedBy=multi-user.target
After restarting gunicorn.service, everything appears to be running fine, gunicorn.service and nginx.service are active ping mysite is working No errors in /var/log/gunicorn/error.log
here is gunicor.log
1629975] [INFO] Booting worker with pid: 1629975
[1629977] [INFO] Booting worker with pid: 1629977
[1629976] [INFO] Booting worker with pid: 1629976
[1628940] [INFO] Shutting down
[1628939] [INFO] Shutting down
[1628937] [INFO] Shutting down
[1628940] [INFO] Finished server process [1628940]
[1628333] [WARNING] Worker with pid 1628940 was terminated due to signal 15
[1628937] [INFO] Finished server process [1628937]
[1628939] [INFO] Finished server process [1628939]
[1628333] [WARNING] Worker with pid 1628937 was terminated due to signal 15
[1628333] [WARNING] Worker with pid 1628939 was terminated due to signal 15
[1629975] [INFO] Started server process [1629975]
[1629977] [INFO] Started server process [1629977]
However, when I try to open the site in a browser, I get: "This page isn’t working"
Why is my Django app not loading in the browser despite Gunicorn and Nginx being active? Is there any misconfiguration in my Gunicorn ASGI setup?