为什么我的websocket在Django Channels App中一直断开连接?

问题描述

我已经花了一个月时间了,没有一个可行的解决方案。一切在生产中都可以正常工作,但是我一直在尝试使用Nginx作为反向代理来部署django-channels应用程序,使服务器保持运行状态的主管,为http请求提供服务的gunicorn,而在使用daphne来处理http请求的weboscket请求部分却陷入了困境。

我是具有unix套接字的bindig:gunicorn.sock和daphne.sock 控制台返回:

WebSocket connection to 'ws://theminglemarket.com/ws/chat/undefined/' Failed: 
Error during WebSocket handshake: Unexpected response code: 500

我的主管配置:

directory=/home/path/to/src
command=/home/path/to/venv/bin/gunicorn_start
user=root
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/path/to/log/gunicorn/gunicorn-error.log

[program:serverinterface]
directory=/home/path/to/src
command=/home/path/to/venv/bin/daphne -u /var/run/daphne.sock chat.asgi:application
autostart=true
autorestart=true
stopasgroup=true
user=root
stdout_logfile = /path/to/log/gunicorn/daphne-error.log

Redis服务器已启动并正在运行,可以确定,使用redis-server 我的Nginx配置:

upstream channels-backend {
#   server 0.0.0.0:8001;
    server unix:/var/run/daphne.sock fail_timeout=0;
}
upstream app_server {
    server unix:/var/run/gunicorn.sock fail_timeout=0;
}
server {
    listen 80;
    listen [::]:80;
    
    server_name theminglemarket.com www.theminglemarket.com;
    keepalive_timeout 5;
    client_max_body_size 4G;
    access_log /home/path/to/logs/Nginx-access.log;
    error_log /home/path/to/logs/Nginx-error.log;


    location /static/ {
        alias /home/path/to/src/static/;
        # try_files $uri $uri/ =404;
    }
    location / {
        try_files $uri @proxy_to_app;
    }
    location /ws/ {
        try_files $uri @proxy_to_ws;
    }
    location @proxy_to_ws {
        proxy_pass http://channels-backend;

        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;
    }
    location @proxy_to_app {
        proxy_pass http://app_server;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        # we don't want Nginx trying to do something cLever with
        # redirects,we set the Host: header above already.
        proxy_redirect off;
    }
}

请询问是否需要其他任何内容,我会尽快更新。谢谢。 这是一个聊天应用程序,您是否认为我应该只使用daphne,我是否正在考虑可伸缩性,所以这就是为什么我使用gunicorn来服务于HTTP请求。在ubuntu服务器上托管

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)