Digital Ocean 上的负载均衡 Websockets

Load Balancing Websockets on Digital Ocean

我正在尝试配置 Digital Ocean 本机负载均衡器以分配 websockets 流量。我设置规则:

尝试通过负载平衡器连接时,我得到: VM915:1 WebSocket connection to 'ws://{loadbalancerip}:8443/' failed: Connection closed before receiving a handshake response.

直接连接工作正常。

那么如何配置负载均衡器来平衡 websockets 流量?

就 Digital Ocean Load Balancer 不支持开箱即用的 websockets 而言,我不得不购买一个小实例并在其上配置 Nginx 以平衡传入3 台本地计算机之间的流量。

这里是 Nginx 的可能配置,它允许您平衡从 Cloudflare 转发到 8443 端口的 wss 流量:

upstream wss {
# Clients with the same IP are redirected to the same backend
# ip_hash;
# Available backend servers
server 228.228.228.1:8443 max_fails=3 fail_timeout=30s;
server 228.228.228.2:8443 max_fails=3 fail_timeout=30s;
server 228.228.228.3:8443 max_fails=3 fail_timeout=30s;
}

server {
listen 8443 ssl default_server;
listen 443 ssl default_server;
listen [::]:8443 ssl default_server;
include snippets/self-signed.conf;
include snippets/ssl-params.conf;
underscores_in_headers on;

root /var/www/html;

index index.html index.htm index.nginx-debian.html;

server_name _;


    location / {
        # switch off logging
        access_log off;
        try_files $uri $uri/ =404;

        # redirect all HTTP traffic to wss
        proxy_pass https://wss;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass_request_headers      on; 
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header HTTP_CF_IPCOUNTRY $http_cf_ipcountry;

        # WebSocket support (nginx 1.4)
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # Path rewriting
        rewrite /wss/(.*) / break;
        proxy_redirect off;

    }
}