Nginx實現簡易負載均衡

最近看一些高併發解決方案,瞭解了一些常見的處理方案,其中很多方案仍需要在實踐中不斷使用才能深刻理解。今天使用nginx實現了對某個網站的負載均衡。

環境準備

nginx+php,這個不多說。如未配置,可以參考wnmp環境配置,這個寫的比較清晰簡單。

第一步 配置測試域名

首先在nginx下配置一個域名(load-balance.com),監聽某個端口(10001),用來測試,並在路徑(E:/wnmp/code/load-balance)下放一個用於測試的html文件,這裏我使用的是nginx的歡迎頁面
配置如下:

server {
        listen       10001;
        server_name  load-balance.com;

        location / {
            root   E:/wnmp/code/load-balance;
            index  index.html index.htm index.php;
        }

        location ~ \.php$ {
            root          E:/wnmp/code/load-balance;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }

第二步 配置多服務器

首先,因爲使用的是同一臺機器,所以,通過多端口來模擬實現多服務器。配置三個監聽其它端口(8081,8082,8083)的server 。
配置如下:

    server {
        listen       10081 default_server;
        server_name  _;
        root   E:/wnmp/code/load-balance;
        index  index.html index.htm index.php;
        location /
        {
                add_header REAL_SERVER 10081;
        }
    }
    server {
        listen       10082 default_server;
        server_name  _;
        root   E:/wnmp/code/load-balance;
        index  index.html index.htm index.php;
        location /
        {
                add_header REAL_SERVER 10082;
        }
    }
    server {
        listen       10083 default_server;
        server_name  _;
        root   E:/wnmp/code/load-balance;
        index  index.html index.htm index.php;
        location /
        {
                add_header REAL_SERVER 10083;
        }
    }

其中 add_header REAL_SERVER 8083; 是在頭信息中增加一個標識來區別不同的server。

第三步 增加一組新的負載組(是自己的理解,這麼叫了 意會就行)

在http中增加配置(如果是多臺獨立服務器,把server對應的域名和端口換掉即可),如下

http {
    ...
    upstream load_balance_cluster
    {
            server 127.0.0.1:10081 weight=11;
            server 127.0.0.1:10082 weight=12;
            server 127.0.0.1:10083 weight=13;
    }
    ...
}

upstream 是關鍵字,load_balance_cluster類似變量,隨便起的,後面的weight是比重,可以不寫,默認相同,即使用三個server的概率相同。

第四步 在配置中是用負載組

在第一步的域名配置中,在location下增加 proxy_pass http://load_balance_cluster;
修改後具體配置如下:

server {
        listen       10001;
        server_name  load-balance.com;

        location / {
            proxy_pass   http://load_balance_cluster;
            root   E:/wnmp/code/load-balance;
            index  index.html index.htm index.php;
        }

        location ~ \.php$ {
            root          E:/wnmp/code/load-balance;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }

配置完成,測試 load-balance.com:10001。如下圖
測試一
測試二
image

看到在header裏 REAL_SERVER 分別是 10083、10082、10081,實現將一個網站使用三個不同server進行負載。

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