django uwsgi nginx websocket 搭建后台管理,本地没问题,上传服务器 websocket 报 502 错误,其他接口能正常访问

2021-04-20 10:58:20 +08:00
 alittlecode

nginx 配置: server { listen 80; server_name 服务器地址; charset utf-8; client_max_body_size 75M;

location / {
    root /root/dist;
    index index.html;
    try_files $uri $uri/ /index.html;
   
}
location /api/ {
    uwsgi_pass 127.0.0.1:8001;
    include /etc/nginx/uwsgi_params;  
}
location /ws/ {
    proxy_pass http://127.0.0.1:8001;
    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;
   
}

} nginx 配置:

[uwsgi]
chdir = /root/....
home = /root/....
module = ....

master = True
processes = 2
harajiri = 60
max-requests = 5000

socket = 127.0.0.1:8001
uid = root
gid = root
pidfile = /root/master.pid
daemonize = /root/conf/logs/uwsgi_hzmj.log
vacuum = True
log-maxsize = 102400 
buffer-size = 65536

websocket 报错:

WebSocket connection to 'ws://服务器地址 /ws/index/data/' failed: Error during WebSocket 		handshake: Unexpected response code: 502
2167 次点击
所在节点    Python
26 条回复
alittlecode
2021-04-20 16:44:41 +08:00
@Latin 我添加完 http-websockets 这个参数还是不行,现在用 gunicorn 可以实现了,但是 30 秒就自动断开了,唉,处处是坑
Aprilming
2021-04-20 18:10:01 +08:00
哈哈,我也遇到过,我用的 daphne 解决的 , /ws/和你一样用 nginx 映射到 127.0.0.1:8088, 然后起一个 daphne:daphne xxx(项目).asgi:application -b 127.0.0.1 -p 8088 。用 supervisord 守护进程之后,目前来看没得什么问题,实践中也没有发现什么问题,但是对性能有没有什么消耗,就不得而知了
Aprilming
2021-04-20 18:12:42 +08:00
@alittlecode #19 我也试过 uwsgi 的 websocket, 奈何当时实在是没有成功,如果你成功了,能否分享一下经验,非常感谢。
alittlecode
2021-04-20 18:13:38 +08:00
@Aprilming 使用 daphne 再启动一个 asgi 服务是吧,我看到这个方法了,但是觉得太麻烦了,直接使用 gunicorn 可以了
alittlecode
2021-04-20 18:15:52 +08:00
@Aprilming 但是现在还有个问题是 30 秒自动断开了,我看有说 nginx 设置 proxy_read_timeout time 参数的,不过貌似这影响性能,没去试,暂时还没解决
Aprilming
2021-04-20 18:16:15 +08:00
@alittlecode #24 gunicorn 问题不大,因为之前考虑到 uwsgi 使用套接字性能比端口转发要好, 所以最后还是使用了 uwsgi+daphne 。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/771852

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX