I. Preface
In the previous article, websocket is used for real-time communication in the project, but the production environment also uses the deployment mode of django+nginx+uwsgi. We all know that uwsgi can't handle websocket requests, so asgi server is needed to handle websocket requests. The official recommended asgi server is daphne. The detailed deployment steps are described below.
II. Software installation
I have written a piece about the deployment mode of django+nginx+uwsgi before. Address: https://www.cnblogs.com/wdliu/p/8932816.html , which will not be discussed here. The following describes the installation configuration of daphne, supervisor, and nginx proxy websocket.
1. Deploy daphne
Create the asgi.py file under the project configuration file directory (the same level as wsgi.py) and add it to the application:
""" ASGI entrypoint. Configures Django and then runs the application defined in the ASGI_APPLICATION setting. """ import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") django.setup() application = get_default_application()
Start daphne test for normal operation (exit after success)
daphne -p 8001 devops.asgi:application
2. Install supervisor
Supervisor is a process management tool implemented by python, which can ensure that the managed process runs all the time, and supervisor will restart automatically when the process is interrupted.
Installation steps:
#yum Installation: yum install python-setuptools easy_install supervisor //perhaps yum install -y epel-release yum install -y supervisor #Manual installation: wget https://pypi.python.org/packages/source/s/supervisor/supervisor-3.1.3.tar.gz tar zxf supervisor-3.1.3.tar.gz cd supervisor python setup.py install #pip Installation: pip install supervisor
Build profile
echo_supervisord_conf > /etc/supervisord.conf
3. Use supervisor to manage daphne process
Edit / etc / supervisor.conf to add configuration
[program:daphne] directory=/opt/app/devops #Project directory command=daphne -b 127.0.0.1 -p 8001 --proxy-headers devops.asgi:application #Start command autostart=true autorestart=true stdout_logfile=/tmp/websocket.log #Journal redirect_stderr=true
Start supervisor
supervisord -c /etc/supervisord.conf
Start or stop daphne
supervisorctl start daphne supervisorctl stop daphne
III. proxy webscoket
Modify nginx configuration file
#####Forwarding configuration upstream wsbackend { server 127.0.0.1:8001; } ######location configuration location /ws/deploy { proxy_pass http://wsbackend; 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; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; }