Nginx負載均衡

1、Nginx負載均衡概述

1.1  應用情況

Nginx做爲一個強大的Web服務器軟件,具有高性能、高併發性和低內存佔用的特點。此外,其也能夠提供強大的反向代理功能。俄羅斯大約有超過20%的虛擬主機採用Nginx作爲反向代理服務器,在國內也有騰訊、新浪、網易等多家網站在使用Nginx作爲反向代理服務器。據Netcraft統計,世界上最繁忙的網站中有11.48%使用Nginx作爲其服務器或者代理服務器。基於反向代理的功能,Nginx作爲負載均衡主要有以下幾點理由:

  • 高併發連接
  • 內存消耗少
  • 配置文件非常簡單
  • 成本低廉
  • 支持Rewrite重寫規則
  • 內置的健康檢查功能
  • 節省帶寬
  • 穩定性高

1.2 性能

Nginx的高併發,官方測試支持5萬併發連接。實際生產環境能到2-3萬併發連接數。10000個非活躍的HTTP keep-alive 連接僅佔用約2.5MB內存。三萬併發連接下,10個Nginx進程,消耗內存150M。淘寶tengine團隊說測試結果是“24G內存機器上,處理併發請求可達200萬”。

 

2、Nginx負載均衡模塊介紹

Nginx實現負載均衡用到了proxy_pass代理模塊核心配置, 將客戶端請求代理轉發至一組upstream虛擬服務池

ngx_http_upstream_module模塊

2.1 配置語法

Syntax:upstream name { ... }
Default:—
Context:http

2.2 配置示例

upstream backend {
       server backend1.example.com       weight=5;
       server backend2.example.com:8080;
       server unix:/tmp/backend3;

       server backup1.example.com:8080   backup;
       server backup2.example.com:8080   backup;
}

server {
     location / {
        proxy_pass http://backend;
    }
}

 

3、負載均衡使用案例

3.1 後端服務器部署

1. 安裝nginx服務

[root@Web-Node1 ~]# yum -y install nginx

2. 編輯虛擬主機(由於主機數量限制,此處我使用虛擬主機)

[root@Web-Node1 ~]# cat /etc/nginx/conf.d/LB.conf
server {
    listen 8081;
    root /soft/code1;
    index index.html;
}

server {
    listen 8082;
    root /soft/code2;
    index index.html;
}

server {
    listen 8083;
    root /soft/code3;
    index index.html;
}

3. 準備訪問web頁面

[root@Web-Node1 ~]# mkdir /soft/{code1,code2,code3} -p
[root@Web-Node1 ~]# echo " <h1> Code1 192.168.1.22:8081 </h1> "  >/soft/code1/index.html
[root@Web-Node1 ~]# echo " <h1> Code2 192.168.1.22:8082 </h1> "  >/soft/code2/index.html
[root@Web-Node1 ~]# echo " <h1> Code3 192.168.1.22:8083 </h1> "  >/soft/code3/index.html

4. 重啓nginx服務

[root@Web-Node1 ~]# systemctl start nginx
[root@Web-Node1 ~]# systemctl restart nginx

3.2 前端負載均衡配置

1. 安裝nginx服務

[root@LB01-Master ~]# yum -y install nginx

2. 配置nginx反向代理

[root@LB01-Master ~]# cat /etc/nginx/conf.d/proxy.conf
upstream proxy {
    server 192.168.1.22:8081;
    server 192.168.1.22:8082;
    server 192.168.1.22:8083;
}

server {
    server_name 192.168.1.20;
    listen 80;
    location / {
        proxy_pass http://proxy;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

3. 重啓nginx服務

[root@LB01-Master ~]# systemctl start nginx
[root@LB01-Master ~]# systemctl enable nginx

3.3 客戶端測試

[root@Client ~]# curl http://192.168.1.20
<h1> Code1 192.168.1.22:8081 </h1>
[root@Client ~]# curl http://192.168.1.20
<h1> Code2 192.168.1.22:8082 </h1>
[root@Client ~]# curl http://192.168.1.20
<h1> Code3 192.168.1.22:8083 </h1>

 

此時是輪詢狀態

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章