nginx对指定端口的TCP和UDP协议进行负载均衡

nginx既可以对tcp协议进行负载均衡,也可以对UDP协议进行负载均衡。
以shadowsock为例,假如我现在有3台shadowsocks:

11.11.11.11:2222
33.33.33.33:4444
55.55.55.55:6666

每台上都同时开了TCP和UDP协议。而且每台上的加密方式和密码都一样。
这点很重要,每台上的加密方式和密码必须一样。
现在我要通过本地nginx实施负载均衡。
以最简单的轮询式(Round Robin)负载为例。
以Debian为例,先安装nginx:

sudo apt install nginx-full -y

修改如下ip和端口,追加到/etc/nginx/nginx.conf 文件中:

# https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/
# 放置在/etc/nginx/nginx.conf的 http{} 部分的下面
stream {
    upstream shadowsocks_tcp {
        # By default, NGINX uses the Round Robin algorithm to load balance traffic
        server 11.11.11.11:2222 max_fails=2 fail_timeout=5;
        server 33.33.33.33:4444 max_fails=2 fail_timeout=5;
        server 55.55.55.55:6666 max_fails=2 fail_timeout=5;
    }
    
    upstream shadowsocks_udp {
        # By default, NGINX uses the Round Robin algorithm to load balance traffic
        server 11.11.11.11:2222 max_fails=2 fail_timeout=5;
        server 33.33.33.33:4444 max_fails=2 fail_timeout=5;
        server 55.55.55.55:6666 max_fails=2 fail_timeout=5;
    }
    
    server {
		# https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-health-check/
        listen        8388;
        proxy_pass    shadowsocks_tcp;
        proxy_timeout 3s;
        proxy_connect_timeout 1s;
    }
    
    server {
		# https://docs.nginx.com/nginx/admin-guide/load-balancer/udp-health-check/
        listen     8388 udp;
        proxy_pass shadowsocks_udp;
		proxy_timeout   1s;
    }
}

重启nginx使配置生效:

sudo systemctl start nginx.service

然后就可以通过配置ss连接到nginx的8388端口 ,均匀的访问到每个节点。

Leave a Reply

Your email address will not be published. Required fields are marked *