1. 程式人生 > >Nginx學習筆記06負載均衡之(一)負載均衡介紹

Nginx學習筆記06負載均衡之(一)負載均衡介紹

最終 反向 結果 html proxy mime cnblogs 負載 cal

1.1.1. 負載均衡的介紹

Nginx中使用upstream配置塊,可以方便的配置出一個基於反向代理的負載均衡解決方案。

upstream中可以包含多個server配置項,每個server配置項指定一個主機地址和端口號,代表一個主機(上遊服務器)

proxy_pass配置反向代理時,可以不指定最終的主機地址,而是只指定upstream配置塊指定的引用名稱。在本文中,upstream配置了一個包含三個主機地址的負載均衡主機集群。

配置內容:

http {

include mime.types;

default_type application/octet-stream;

upstream tomcat {

server tomcat101.coe2coe.me:8080;

server tomcat141.coe2coe.me:8080;

server tomcat142.coe2coe.me:8080;

}

server {

listen 8000;

server_name ng.coe2coe.me;

location / {

root html;

index index.html;

}

location ~ ^/hello/ {

proxy_pass http://tomcat;

}

}

}

運行結果:

在瀏覽器中訪問http://ng.coe2coe.me:8000/hello/時,將會根據主機是否可用的狀態,默按照upstream配置的次序依次選擇其中一臺主機進行請求和響應的轉發。

以下三張圖片是nginx啟動後前三次訪問(Ctrl+F5)時的結果:

默認使用依次輪詢策略,依次選用的主機是tomcat101, tomcat141,tomcat142

1次訪問:

技術分享

2次訪問:

技術分享

3次訪問:

技術分享

在將tomcat141主機(192.168.197.141)tomcat服務關閉後,將不會看到來自tomcat141的響應頁面。有時候會出現多次請求僅轉發到同一個主機的情況,比如Ctrl+F5多次,都是請求的tomcat142,而不見有tomcat101

Nginx學習筆記06負載均衡之(一)負載均衡介紹