Nginx深刻了解-進階(三)

Nginx負載均衡(Load Balance,簡稱LB)是一種服務器或網絡設備的集羣技術。負載均衡將特定的業務(網絡服務、網絡流量等)分擔給多個服務器或網絡設備,從而提升了業務處理能力,保證了業務的高可用性。

Nginx負載均衡示意圖:php

nginx

Nginx負載均衡原理就是將全部客戶端的請求經過proxy_pass代理轉發到對應的一組後端服務器upstream server上。html

配置語法:
Syntax:upstream name {...}

Default:--nginx

Context:http算法

配置實例:

後端服務器組upstream server後端

#server1
server {
    listen 8001;
    server_name localhost;
    access_log /var/logs/nginx/access.log main;

    location / {
        root /opt/app/code;
        index index.html index.htm index.php;
    }
    ...
}
#server2
server {
    listen 8002;
    server_name localhost;
    access_log /var/logs/nginx/access.log main;

    location / {
        root /opt/app/code;
        index index.html index.htm index.php;
    }
    ...
}
#server3
server {
    listen 8003;
    server_name localhost;
    access_log /var/logs/nginx/access.log main;

    location / {
        root /opt/app/code;
        index index.html index.htm index.php;
    }
}

負載均衡服務器main server服務器

#默認使用輪詢機制
upstream test {
    server 114.249.225.223:8001 down;
    server 114.249.225.223:8002 backup;
    server 114.249.225.223:8003 max_fails=1 fail_timeout=30s; // 容許失敗一次,超過30s則直接訪問8002
}
#加權
upstream test {
    server 114.249.225.223:8001;
    server 114.249.225.223:8002;
    server 114.249.225.223:8003 weight=5;
}
#ip_hash
upstream test {
    ip_hash;
    server 114.249.225.223:8001;
    server 114.249.225.223:8002;
    server 114.249.225.223:8003;
}
#url_hash
upstream test {
    hash $request_uri;
    server 114.249.225.223:8001;
    server 114.249.225.223:8002;
    server 114.249.225.223:8003;
}
server {
    listen 80;
    server_name localhost www.mantis.me;

    access_log /var/logs/nginx/access.log main;

    location / {
        proxy_pass http://test;
        include proxy_params;
    }
    ...
}

後端服務器在負載均衡調度中的狀態:網絡

參數 說明
down 當前的server暫時不參與負載均衡
backup 預留的備份服務器
max_fails 容許請求失敗的次數
fail_timeout 通過max_fails失敗後,服務暫停的時間
max_conns 限制最大鏈接數

調度算法:app

算法 說明
輪詢(默認) 按時間順序逐一分配到不一樣的後端服務器
加權輪詢 weight越大,分配到的訪問概率越高
ip_hash 每一個請求按訪問ip的hash結果分配,這樣來自同一個ip的請求將固定訪問到同一個後端服務器
url_hash 按照訪問的url的hash結果來分配請求,是每一個url定向到同一個後端服務器
least_conn 最少鏈接數,哪一個機器鏈接數少就分發到哪一個機器
hash關鍵數值 hash自定義的key
相關文章
相關標籤/搜索