[英]Django channels websocket connecting and disconnecting (Nginx + Daphne + Django + Channels)
我在使用 Nginx + Gunicorn + Daphne + Django 的生產虛擬機中部署它時遇到問題。 我一直在本地虛擬機中對其進行測試,它可以正常工作,但在生產中,套接字正在連接和斷開連接。 我附上了我的 nginx 配置,asgi.py 和 routing.py。 我使用命令````$ daphne -p 8010 project.asgi:application```在這里輸入圖片描述
# Nginx config
upstream test_project {
server localhost:8001;
}
upstream test_project_websocket {
server localhost:8002;
}
server {
listen 1881;
location / {
proxy_pass http://test_project;
}
location /ws/ {
proxy_pass http://test_project_websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_redirect off;
}
proxy_set_header Host $host;
}
#asgi.py
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WebServer.settings')
django.setup()
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter
import Andon.routing # app.routing
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.layers import get_channel_layer
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
Andon.routing.websocket_urlpatterns,
),
),
})
# routing.py
from django.urls import path, re_path
from . import consumers
from channels.layers import get_channel_layer
websocket_urlpatterns = [
re_path(r'ws/andon/$', consumers.AndonConsumer.as_asgi()),
]
編輯 27-11-20:還沒有解決,但發現了一些有趣的東西。 如果您使用的是舊版本的 redis,請確保您擁有以下版本:
channels==3.0.2
channels-redis==2.4.1
編輯 27-11-20:部分解決我想我的 nginx 配置有一些問題,因為如果我嘗試直接連接到 daphne 端口,它工作得很好,但如果我從 nginx 重定向流量,它不會
編輯 16-12-20:解決方案我有一個舊版本的 nginx 1.10,我將它升級到 1.16 並且沒有任何問題,使用這篇文章的配置:配置
這是您要找的配置
# Connecting to daphne socket
upstream test_project_websocket {
server localhost:8010;
}
....
# Notice the "/" at then end of location & proxy_pass url
location /ws/ {
proxy_pass http://test_project_websocket/;
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_pass http://test_project;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.