Network Load Balancing With Nginx

陳勇勳 Jacky Chen

  • 精誠資訊/恆逸教育訓練中心-資深講師
  • 技術分類:網路管理與通訊應用

 

 

現在電腦的運算能力越來越強,單位時間內能夠處理的 Request 也就越來越多,但無論單一台電腦的運算能力再如何的強大,都會有其能力的上限,因此各種不同的架構也就因應而生,其中 NLB 就是其中之一,但這些現成的 NLB ( Network Load Balancing ) 設備通常所費不貲,所幸 OpenSource 界的先進們無私奉獻,創造了足以媲美商用 NLB 設備的軟體 Nginx!

Nginx起初是一個 Web Service,一個以輕巧著名的 Web Service,因此其執行速度非常的快,所以近年有很多的大型網站已慢慢的轉移至 Nginx,Nginx除了是一個非常出色的 Web Service之外也是一個了得的 NLB,底下就讓我們來看看如何使用 Nginx 來部署 NLB。



LAB環境:

  • Load Balancer
    • IP:192.168.1.10
  • Web 1
    • FQDN:www.example.com
    • IP:192.168.1.21
    • FQDN:web1.example.com
  • Web 2
    • IP:192.168.1.22
    • FQDN:web2.example.com
  • Web 3
    • IP:192.168.1.23
    • FQDN:web3.example.com

LAB步驟:

  • 安裝nginx
    • yum install nginx
    • systemct enable nginx –now
    • firewall-cmd --permanent --add-service=http --add-service=https
    • firewall-cmd --reload
  • 修改nginx ( /etc/nginx/nginx.conf )
        ………. 省略 ………….
        
        http {
        
            ………. 省略 ………….
        
                server {
                    listen  	192.168.1.10:80;
                    server_name	www.example.com;
                        
                    access_log	/var/log/nginx/example-access.log main
                    error_log	/var/log/nginx/example-error.log warn;
        
                    location / {
                                    proxy_pass http://web_server;
                    } 
                }
       
                upstream web_server {
                         server	web1.example.com;
                         server	web2.example.com;
                         server	web3.example.com;
                }
             }                        
  • 設定好 DNS Record
  • 使用 curl http://www.example.com進行網頁的瀏覽測試


細節討論:

  1. 在以上的測試中可以發現當用戶端存取 http://www.example.com時,NLB會將請求以循環(round-robin)的方式轉交給後端的 Web Server處理,但如果後端的 Web Server的處理能力不同時,我們可以加入 weigth 參數來分配任務的多寡給後端的 Web Server,如下:

                upstream web_server {
                    server	web1.example.com  weight=6;
                    server	web2.example.com  weight=3;
                    server	web3.example.com  weight=1;
                }                        

    完成以上的設定之後,用戶端對NLB進行存取時,每10次就會有 6 次轉交給 web1處理、3次轉交給web2處理、1次轉給web3處理,如此就能依照後端Web Server的處理能力來分派工作了。

  2. 如果Web Application有使用到 session 時,如何確保用戶端連線上來時每次都能連用同一台後端的 Web Server 呢?

                upstream web_server {
    	        ip_hash;
                    server	web1.example.com;
                    server	web2.example.com;
                    server	web3.example.com;
                }                        

    ip_hash 參數可以依據用戶端的 ip 位置讓相同的用戶端每次都連到同一台後端的 Web Server,如此就無須擔心 session 的問題。

  3. 如果後端某一台Web Server停止服務時會如何呢?這個問題無須擔心!如果後端Web Server停止服務時,Nginx將不會再將請求轉交給該 Web Server,但是當該 Web Server重新上線時,Nginx將會自動的再將請求分派給該 Web Server。




您可在下列課程中了解更多技巧喔!