infrastructure1 min read
Daphne for WebSockets, Gunicorn for HTTP, Nginx in front
This setup uses Gunicorn for ordinary HTTP requests and Daphne for WebSockets, with Nginx routing between them.
Gunicorn's WSGI workers serve the HTTP application. Daphne is an ASGI server that supports WebSockets and can support HTTP/2 with the appropriate dependencies and configuration. Daphne is one option for ASGI traffic, not a requirement for every WebSocket deployment. Gunicorn can also run ASGI applications with a suitable worker class.
Routing by path
In this configuration, Nginx forwards /ws/ to Daphne and everything else to Gunicorn. Daphne can serve HTTP as well, so splitting the traffic is a deployment choice.
upstream server_http {
server backend:8000;
}
upstream server_ws {
server daphne:9001;
}
server {
listen 80;
# ...
location / {
proxy_pass http://server_http;
# ...
}
location /ws/ {
proxy_pass http://server_ws;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# ...
}
# ...
}
Connections under /ws/ go to the daphne service on port 9001. Other requests go to the backend service on port 8000. The WebSocket location forwards the HTTP upgrade headers.