Nginx負載均衡策略

丶小炒肉發表於2016-05-31

  目前nginx負載均衡支援的5種方式的分配

 

1. 輪詢

每個請求按時間順序逐一分配到不同的後端伺服器,如果後端伺服器down掉,能自動剔除.

upstream backserver {

server 192.168.5.205;

server 192.168.5.206;

}

 

2. weight

指定輪詢機率,weight和訪問比率成正比,用於後端伺服器效能不均的情況.

upstream backserver {

server 192.168.5.205 weight=10;

server 192.168.5.206 weight=10;

}

 

3.ip_hash

每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個後端伺服器,可以解決session的問題.

upstream backserver {

ip_hash;

server 192.168.5.205:88;

server 192.168.5.206:80;

}

 

4.fair(第三方)

按後端伺服器的響應時間來分配請求,響應時間短的優先分配.

upstream backserver {

server 192.168.5.205;

server 192.168.5.206;

fair;

}

 

5.url_hash(第三方)

按訪問url的hash結果來分配請求,使每個url定向到同一個後端伺服器,後端伺服器為快取時比較有效.

upstream backserver {

server squid1:3128;

server squid2:3128;

hash $request_uri;

hash_method crc32;

}

 

 

 

---------------------------------------------------------------

在需要使用負載均衡的server中增加

 

proxy_pass http://backserver/;

upstream backserver{

ip_hash;

server 127.0.0.1:9090 down; (down 表示單前的server暫時不參與負載)

server 127.0.0.1:8080 weight=2; (weight 預設為1.weight越大,負載的權重就越大)

server 127.0.0.1:6060;

server 127.0.0.1:7070 backup; (其它所有的非backup機器down或者忙的時候,請求backup機器)

}

max_fails:允許請求失敗的次數預設為1.當超過最大次數時,返回proxy_next_upstream模組定義的錯誤.

 

 

 

 

 

 

 

 

 

Nginx 負載均衡+ 第三方模組,健康狀態檢測

 

 

https://github.com/yaoweibin/nginx_upstream_check_module 下載軟體

需要打補丁,並且重新編譯

解壓 並 打上補丁...

unzip yaoweibin-nginx_upstream_check_module-v0.1.6-17-gdfee401.zip

cd nginx-1.2.3

patch -p1 < /opt/software/yaoweibin-nginx_upstream_check_module-dfee401/check_1.2.1+.patch

(如果nginx版本不是1.2.1以上的,用patch -p1 < /opt/software/yaoweibin-nginx_upstream_check_module-dfee401/check.patch打補丁)  

 

./configure --user=www --group=www --prefix=/opt/local/nginx --with-http_stub_status_module --with-http_ssl_module --add-module=/opt/software/yaoweibin-nginx_upstream_check_module-dfee401/

make && make install 

 

修改配置檔案:

 

 

      upstream webserver {

        server 10.3.0.100:8000 weight=1;

        server 10.3.0.101 weight=2;

 

        check interval=1000 rise=2 fall=2 timeout=1000;  //interval檢測間隔時間,rsie請求2次正常的話為up,fail請求2次失敗的話為down,timeout檢查超時時間(毫秒)  

 check_http_send "GET /.test.html HTTP/1.0";  //所傳送的檢測請求 

 

       }

 

 

 server {  

        listen       80;  

        server_name  localhost;  

        location / {  

     proxy_pass http://peace;  //引用  

        }     

 location /status {   //定義一個類似stub_status的方式輸出檢測資訊  

  check_status;  

 }  

        error_page   500 502 503 504  /50x.html;  

        location = /50x.html {  

            root   html;  

        }  

    }  

相關文章