在生产中运行Django通道和Websocket设置达芙妮和主管



在Nginx和Gunicorn上部署Django应用程序:https://www.youtube.com/watch?v=08yYjLGWzaM&t=942s

通过5个简单的步骤即可使Websocket实时运行(保证)。
我们设置NGINX,supervisor,daphne,asgi.py和redis以确保其正常工作。
如果您的WebSockets在本地运行良好,但在上线生产时遇到了麻烦,则此视频适合您。

通过HTTP构建REST API的问题已经被反复讨论。但是我们可以对WebSockets做同样的事情吗?

档案:
Nginx安装文件

我的nginx conf文件是

上游app_server {
    服务器Unix:/home/urban/run/gunicorn.sock fail_timeout = 0;
}

服务器{

    #在此处添加服务器的IP地址
    #或指向该IP的域(例如example.com或www.example.com)
    server_name YOUR_IP;

    keepalive_timeout 5;
    client_max_body_size 4G;

    access_log /home/urban/logs/nginx-access.log;
    error_log /home/urban/logs/nginx-error.log;

    位置/ static / {
        别名/ home / urban / homet_dj / static /;
    }

    #检查静态文件,如果找不到,则为应用程序代理
    位置 / {
        try_files $ uri @proxy_to_app;
    }

    位置/ ws / {
        try_files $ uri @proxy_to_ws;
    }

    位置@proxy_to_ws {
       proxy_pass http://0.0.0.0:8001;

        proxy_http_version 1.1;
 proxy_set_header升级$ http_upgrade;
        proxy_set_header连接“升级”;

        proxy_redirect关闭;
        proxy_set_header主机$ host;
        proxy_set_header X-Real-IP $ remote_addr;
        proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;
        proxy_set_header X转发的主机$ server_name;
    }

    位置@proxy_to_app {
      proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;
      proxy_set_header主机$ http_host;
      proxy_redirect关闭;

}

Supervisor.conf文件

[program:homet_dj]
命令= / home / urban / bin / gunicorn_start
用户=城市
autostart = true
autorestart = true
redirect_stderr = true
stdout_logfile = / home / urban / logs / gunicorn-error.log

[program:serverinterface]
命令= daphne -b 0.0.0.0 -p 8001 homet_dj.asgi:应用程序
目录= / home / urban / homet_dj /
autostart = true
autorestart = true
stopasgroup = true
用户=城市
stdout_logfile = /home/urban/logs/gunicorn-error.log

websocket调用文件:
var socket = new WebSocket(“ wss://YOUR_IP.com/ws/notify”)

socket.onopen = function(){
    console.log(’connected’);
    console.log(’connected’);
}
socket.onmessage = function(data){
    console.log(’onmaeesge’);
    console.log(data);
}
socket.onclose =函数(数据){
    console.log(’onclose’);
    console.log(data);

socket.onerror =函数(数据){
    console.log(’错误’);
    console.log(data);
}
}。

7 comments
  1. Can you tell me resources from where you got this information? This is very interesting and I want to read more about deploying my Django app that uses Channels to production

Comments are closed.