阿里云下配置nginx+websocket+flask+gunicorn

本机调试OK的websocket,上了阿里云,总是有这样那样的问题。

比较好的方案是,自己使用nginx反代来完成。

具体配置如下:

nginx配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
server {
listen 80;
listen [::]:80;
server_name example.com;
access_log /srv/www/example.com/logs/access.log;
error_log /srv/www/example.com/logs/error.log;
location / {
proxy_pass http://127.0.0.1:26666;
}
location /ws_* {
proxy_pass http://127.0.0.1:26666;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location ~ /\.ht {
deny all;
}
}

根据nginx的官方资料,nginx一般不会主动转发header中带有UpgradeConnection的HTTP请求。

所以,需要上面比较关键的那部分:

1
2
3
4
5
6
location /ws_* {
proxy_pass http://127.0.0.1:26666;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}

PS: 如果websocket逻辑里面没有心跳包的设计,最好修改下proxy_connect_timeout到一个合理的值。

默认是60s。

gunicorn 启动

这个比较简单:

1
gunicorn -b 127.0.0.1:26666 your_entry:app_name

PS