用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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM