修复Daphne、Redis、Nginx配置,解决前端WebSocket连接失败问题
问题背景
在DigitalOcean Droplet上部署了Django+Channels+Daphne+Nginx+Gunicorn的HTTPS服务,HTTP交互正常,但WebSocket连接报错:WebSocket connection to 'wss://www.DomainURL/ws/chat/2/' failed: There was a bad response from the server,本地开发环境正常,所有服务状态无报错。
核心修复步骤
1. 修正Daphne服务配置(无需自行处理SSL)
当前Daphne配置中存在证书路径拼写错误(mydomian.com应为DomainURL),且Nginx已负责HTTPS终结,Daphne只需监听本地HTTP端口即可,简化配置:
修改Daphne.service:
[Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/user/project # 改为监听本地HTTP端口,无需SSL ExecStart=/home/user/project/venv/bin/daphne -b 127.0.0.1 -p 8001 project.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target
重启Daphne服务:
systemctl daemon-reload systemctl restart daphne.service
2. 完善Nginx的WebSocket反向代理配置
当前Nginx的/ws/ location缺少必要的请求头和超时设置,补充后确保WebSocket握手和连接稳定:
修改/etc/nginx/sites-available/project中的location /ws/块:
location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; 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-Proto $scheme; # 增加超时设置,避免连接被过早断开 proxy_connect_timeout 7d; proxy_send_timeout 7d; proxy_read_timeout 7d; proxy_redirect off; proxy_pass http://127.0.0.1:8001; }
重启Nginx服务:
systemctl restart nginx
3. 验证Redis服务状态
Channels依赖Redis作为通道层,确认Redis正常运行:
systemctl status redis-server # 如果未运行,启动Redis systemctl start redis-server systemctl enable redis-server
4. 检查Daphne端口监听状态
确认Daphne正在监听127.0.0.1:8001:
ss -tulpn | grep 8001
5. 确认Django路由匹配
当前routing.py中的正则表达式r'ws/chat/(?P<user_id>\d+)/'与前端请求的/ws/chat/2/完全匹配,无需修改,但需确保没有其他Django路由与/ws/前缀冲突。
验证
完成上述修改后,刷新前端页面,检查控制台是否显示WebSocket is connected,同时可通过Daphne日志查看连接情况:
journalctl -u daphne.service -f
内容的提问来源于stack exchange,提问作者CASH HOLLISTER

