用Nginx为多个http/socks代理做负载均衡,反向代理

近日遇到一个需求,某机器上在四个端口上开了四个http代理,因为每个代理都有流量限额,所以要平均着使用,但由使用者手动更改端口号又太麻烦,所以需要将这4个端口融合为1个,想到的办法就是用Nginx做负载均衡。

Nginx负载均衡的文章教程有很多了,但多数使用背景都是网站服务器分流,方法基本是对nginx.conf的http{ 下添加upstream xxxx等等,经实验证明是不管用的,需要nginx的stream模块才可以。下面进行介绍。

nginx.conf的错误配置

http {


    ........

    upstream local-proxy  {
        server 127.0.0.1:8119; #union-proxy
        server 127.0.0.1:8120; #union-proxy
        server 127.0.0.1:8121; #union-proxy
        server 127.0.0.1:8122; #union-proxy
        ip_hash;
    }
 
    server {
        listen 8118;
        server_name  http-proxy;
 
        location / {
        proxy_pass  http://local-proxy;
      }
    ......

}

虽然感觉http代理应该写在http模块里,但事实证明是是不行的。而改用stream模块后,不光http代理可以,sock5代理也行。

nginx.conf正确配置

stream {

    ......

    upstream local-proxy  {
        server 127.0.0.1:8119; #union-proxy
        server 127.0.0.1:8120; #union-proxy
        server 127.0.0.1:8121; #union-proxy
        server 127.0.0.1:8122; #union-proxy
        #ip_hash在stream中是不支持的
    }
 
    server {
        listen 8118;
        #server_name也没有;
        proxy_pass local-proxy;
 
    }
    ......
}

之后重载配置或重启nginx,用curl测试:

curl -x 127.0.0.1:8118 http://icanhazip.com

发现出口IP已经变了,多次请求发现IP不一致,负载均衡成功。

有关stream模块详情还可参见 https://www.zybuluo.com/orangleliu/note/478334 有更详细的配置方法。

另,nginx -t -c /etc/nginx/nginx.conf 命令可方便地检查配置文件是否有问题。

本文的需求如果不想用Nginx,Haproxy也可以做到,可参见 https://zhuanlan.zhihu.com/p/30559435