django+uwsgi+daphne+supervisor生产环境部署

项目中使用了webscoket进行实时通讯,但是生产环境又使用了django+nginx+uwsgi的部署方式,我们都知道uwsgi并不能处理websocket请求,所以需要asgi服务器来处理websocket请求,官方推荐的asgi服务器是daphne

1. 部署daphne

使用pip install daphne 的方式安装

项目配置文件目录(settings.py同级)下创创建文件asgi.py,加入应用:

"""
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")  # myproject ==> 项目名称
django.setup()
application = get_default_application()

启动daphne 测试是否正常运行(成功以后退出)

daphne -b 127.0.0.1 -p 8001 devops.asgi:application # devops ==> 项目名称

2.安装supervisor

supervisor是由python实现的一个进程管理工具,可以确保所管理的进程一直运行,当进程一点中断supervisord会自动进行重启。

#yum安装:
yum install python-setuptools
easy_install supervisor
或者
yum install -y epel-release
yum install -y supervisor  

#手动安装:
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安装:
pip install supervisor

# 生成配置文件
echo_supervisord_conf > /etc/supervisord.conf

3. 使用supervisor管理daphne进程

编辑/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

4.代理webscoket

修改nginx配置文件

#####转发配置  放在http 下级 server 同级

upstream wsbackend {
         server 127.0.0.1:8001;
}

######location配置 放在 server  下级

 location /ws/deploy {            # deploy ==> channel 路由开头
        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;
  }
上一篇
下一篇
Copyright © 2022 Egon的技术星球 egonlin.com 版权所有 帮助IT小伙伴学到真正的技术