我正在使用docker compose来构建一个django,Nginx作为服务的项目.当我启动daphne服务器,并且客户端尝试连接到websocket服务器时,我收到此错误:
*1 recv() Failed (104: Connection reset by peer) while reading response header from upstream
客户端显示了这一点
Failed: Error during WebSocket handshake: Unexpected response code: 502
这是我的docker-compose.yml
version: '3'
services:
Nginx:
image: Nginx
command: Nginx -g 'daemon off;'
ports:
- "1010:80"
volumes:
- ./config/Nginx/Nginx.conf:/etc/Nginx/Nginx.conf
- .:/makeup
links:
- web
web:
build: .
command: /usr/local/bin/circusd /makeup/config/circus/web.ini
environment:
DJANGO_SETTINGS_MODULE: MakeUp.settings
DEBUG_MODE: 1
volumes:
- .:/makeup
expose:
- '8000'
- '8001'
links:
- cache
extra_hosts:
"postgre": 100.73.138.65
Nginx的:
server {
listen 80;
server_name thelab518.cloudapp.net;
keepalive_timeout 15;
root /makeup/;
access_log /dev/stdout;
error_log /dev/stderr;
location /api/stream {
proxy_pass http://web:8001;
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 / {
try_files $uri @proxy_to_app;
}
location @proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://web:8000;
}
而circusd的web.ini文件:
[watcher:web]
cmd = /usr/local/bin/gunicorn MakeUp.wsgi:application -c config/gunicorn.py
working_dir = /makeup/
copy_env = True
user = www-data
[watcher:daphne]
cmd = /usr/local/bin/daphne -b 0.0.0.0 -p 8001 MakeUp.asgi:channel_layer
working_dir = /makeup/
copy_env = True
user = root
[watcher:worker]
cmd = /usr/bin/python3 manage.py runworker
working_dir = /makeup/
copy_env = True
user = www-data
最佳答案
非常明确地说stated in the fine manual,要成功运行Channels,您需要有一个专用的应用服务器来实现ASGI协议,例如提供的
原文链接:https://www.f2er.com/nginx/434453.htmldaphne
使用Channels更改了整个Django执行模型,因此有单独的“接口服务器”负责接收和发送消息,例如,WebSockets或HTTP或SMS,以及运行实际代码的“工作服务器”(可能在不同的服务器或VM或容器上或…).这两者通过“通道层”连接,该通道层来回传送消息和回复.
当前实现提供3个通道层,用于在接口服务器和工作服务器之间通信ASGI:
>内存中的通道层,主要用于运行测试服务器(它是单个进程)
>基于IPC的通道层,可用于在同一服务器上运行不同的工作程序
>基于redis的通道层,应该用于繁重的生产站点,能够将接口服务器连接到多个工作服务器.
你像配置DATABASES一样配置它们::
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgi_redis.RedisChannelLayer","ROUTING": "my_project.routing.channel_routing","CONFIG": {
"hosts": [("redis-channel-1",6379),("redis-channel-2",6379)],},}
当然这意味着您的docker配置必须更改并添加一个或多个接口服务器,而不是Nginx(或者除此之外)(即使在这种情况下,您需要在不同的端口上接受所有的端口上的websocket连接)连接可能的问题)并且很可能是redis的一个实例连接它们.
这反过来意味着在circus和Nginx支持ASGI之前,不可能将它们与django-channels一起使用,或者这种支持只适用于系统的常规http部分.
您可以在Deploying section of the official documentation中找到更多信息.