1. 程式人生 > >django+uwsgi+daphne+supervisor生產環境部署

django+uwsgi+daphne+supervisor生產環境部署

一、前言

  在上一篇文章中專案中使用了webscoket進行實時通訊,但是生產環境又使用了django+nginx+uwsgi的部署方式,我們都知道uwsgi並不能處理websocket請求,所以需要asgi伺服器來處理websocket請求,官方推薦的asgi伺服器是daphne,下面將介紹詳細的部署步驟。

 

二、軟體安裝

  之前已經寫過一一篇關於django+nginx+uwsgi的部署方式地址:https://www.cnblogs.com/wdliu/p/8932816.html,這裡就不多說了,以下介紹daphne、supervisor、以及nginx代理websocket的安裝配置。

1.部署daphne

專案配置檔案目錄(wsgi.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") django.setup() application = get_default_application()

啟動daphne 測試是否正常執行(成功以後退出)

daphne -p 8001 devops.asgi:application

 

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

 

三、代理webscoket

修改nginx配置檔案

#####轉發配置

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;
  }