In production, your code must connect to wss
. However, unless you have created an alternate server running a websocket, you must use something to redirect traffic like Daphne. Daphne is used to run multiple instances or python applications and redirect web traffic on a specific port. The port we are redirecting traffic on must be setup in the server configuration. Please read the Daphne documentation for more info.
After you have setup up Daphne, you are going to want to setup your server configuration to redirect traffic to the ports you are using for https
and wss
. Remember, each Daphne instance is local to our server, thus we need to redirect all to wss
to ws
. Because we are using Daphne to run asynchronous applications, we no longer specify a WSGIScriptAlias
WSGIDaemonProcess
or WSGIProcessGroup
but instead specify the asgi file to Daphne when we run the server. For example in Apache2:
...
RewriteEngine on
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR]
RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
RewriteRule .* ws://127.0.0.1:8001%{REQUEST_URI} [P,QSA,L]
ProxyPass /wss/ wss://127.0.0.1:8001/
ProxyPassReverse /wss/ wss://127.0.0.1:8001/
...
SSLEngine on
SSLCertificateFile /etc/ssl/certificate.crt
SSLCertificateKeyFile /etc/ssl/private/private.key
SSLCertificateChainFile /etc/ssl/ca_bundle.crt
...
Then you have to start the server, and so at production level you are going to need a Docker container or some methodology to keep the code running. Make sure to modify the port in production level to match your apache conf.
daphne -b 0.0.0.0 -p 8001 django_project.asgi:application // Local Development Level
daphne -e ssl:443:privateKey=key.pem:certKey=crt.pem django_project.asgi:application // Production Level