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 上

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Asurplus

学如逆水行舟,不进则退

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值