Nginx配置websocket协议
什么是websocket
WebSocket
是一种网络通信协议,旨在为客户端和服务器之间提供全双工(full-duplex)通信。与传统的HTTP
通信不同,WebSocket
允许在单个连接上进行双向数据传输,适用于实时应用程序。
HTTP vs Websocket
- http 协议请求流程(简图)
- websocket 协议请求流程(简图)
配置要点
- websocket开始连接的时候,客户端会给服务器发起一个
HTTP
请求,请求头中包含Upgrade:websocket
和connection:Upgrade
。nginx
需要把请求头中的这些信息转发给后端的websocket
服务。 websocket
需要使用http/1.1
协议,所以需要在配置中指定proxy_http_version 1.1
。- 如上图所示,
websocket
是长连接,所以需要在配置中设置一个timeout
,避免连接被nginx
自动关闭。
配置websocket
当需要通过nginx
反代websocket
服务时,我们需要在nginx
配置中做一些修改,因为nginx
默认是不支持websokcet
协议的。
- 常规配置
server {
listen 80;
server_name xp.sb;
location /ws/ {
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400s; # 24 hours
proxy_send_timeout 86400s; # 24 hours}
}
}
- 负载均衡
upstream ws_backend {
server 10.0.0.1:8080;
server 10.0.0.2:8080;
server 10.0.0.3:8080;
}
server {
listen 80;
server_name xp.sb;
location /ws/ {
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400s; # 24 hours
proxy_send_timeout 86400s; # 24 hours}
# 确保客户端始终连接到同一个后端服务器
ip_hash;
}
}
- 连接数限制
localtion /ws/ {
....
# 每个ip最多保持10个ws连接
limit_conn conn_per_ip 10;
}
# http 块中定义连接限制区
http {
...
limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m
...
}
- 缓冲区配置
location /ws/ {
...
proxy_buffer_size 16k;
proxy_buffer 4 32k;
proxy_busy_buffers_size 64;
}
- 心跳检测配置
location /ws/ {
...
proxy_websocket_keepalive_timeout 20;
proxy_websocket_keepalive_interval 5;
}
SSL配置
server { listen 443 ssl; http2 on; server_name xp.sb; ssl_certificate /usr/local/nginx/conf/ssl/xp.sb/fullchain.cer; ssl_certificate_key /usr/local/nginx/conf/ssl/xp.sb/xp.sb.key; location /ws/ { proxy_pass http://websocket_backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 86400s; # 24 hours proxy_send_timeout 86400s; # 24 hours} } }