Configuring asgi to achieve can handle websocket

Used in the project the webscoket communicate in real time, but the production and use django + nginx + uwsgi of deployment, we all know uwsgi not handle websocket request, so it is necessary asgi server to handle websocket request, the official recommended asgi server daphne

1. Deploy daphne

Create a file asgi.py project under the profile directory (wsgi.py the same level), adding applications:

"""
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()
启动daphne 测试是否正常运行(成功以后退出)
daphne -p 8001 devops.asgi:application

2. Install supervisor

  supervisor is a process management tool implemented by the python, you can ensure that the management of the process has been run, when the intake 
supervisord will restart automatically process a little break.
installation steps

yum install:

yum install python-setuptools
easy_install supervisor
或者
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 install:

pip install supervisor
生成配置文件
echo_supervisord_conf > /etc/supervisord.conf

3. Use the supervisor process management daphne

Join the configuration editor /etc/supervisord.conf

[program:daphne]
directory=/opt/app/devops  #项目目录
command=daphne -b 127.0.0.1 -p 8001 --proxy-headers devops.asgi:application #启动命令
autostart=true
autorestart=true
stdout_logfile=/tmp/websocket.log  #日志
redirect_stderr=true
启动supervisor
supervisord -c /etc/supervisord.conf
启动或者停止daphne
supervisorctl start daphne
supervisorctl stop daphne

Third, the agent webscoket
modify nginx configuration file

/#####转发配置

upstream wsbackend {
         server 127.0.0.1:8001;
}

/######location配置
 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;
  }

Guess you like

Origin www.cnblogs.com/0916m/p/11481914.html