Nginx反向代理WebSocket,


我们的 WebSocket 服务实现了集群模式,则需要使用 Nginx 代理转发 WebSocket 实现负载均衡的效果,配置如下:

  • 1、原始配置文件如下:
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
	
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

}
  • 2、加入 WS 后:
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
	
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

	# WS server
	map $http_upgrade $connection_upgrade {
		default upgrade;
		'' close;
	}

	upstream wsbackend {
		server 127.0.0.1:6789;
		server 127.0.0.1:6790;
		keepalive 1000;
	}

	server {
		listen 20038;
		server_name game.wqddz.com;
		
		location / {
			proxy_http_version 1.1;
			proxy_pass http://wsbackend;
			proxy_redirect off;
			proxy_set_header Host $host;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_read_timeout 3600s;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header Upgrade $http_upgrade;
			proxy_set_header Connection $connection_upgrade;
		}
	}
}

此时,访问 ws://localhost:20038 就会被转发到 127.0.0.1:6789 和 127.0.0.1:6790 上

如您在阅读中发现不足,欢迎留言!!!

相关内容