lvs調度算法和nginx常用模塊

1、簡述LVS調度方案及應用場景
2、詳細描述nginx模塊並舉例說明

1、簡述LVS調度方案及應用場景

lvs的調度算法:

靜態方法:僅根據算法本身進行調度;
    RR:roundrobin,輪詢;
    WRR:Weighted RR,加權輪詢;
    SH:Source Hashing,實現session sticky,源IP地址hash;將來自於同一個IP地址的請求始終發往第一次挑中的RS,從而實現會話綁定;
    DH:Destination Hashing;目標地址哈希,將發往同一個目標地址的請求始終轉發至第一次挑中的RS,典型使用場景是正向代理緩存場景中的負載均衡;

動態方法:主要根據每RS當前的負載狀態及調度算法進行調度;
    Overhead=

    LC:least connections
        Overhead=activeconns*256+inactiveconns
    WLC:Weighted LC
        Overhead=(activeconns*256+inactiveconns)/weight
    SED:Shortest Expection Delay
        Overhead=(activeconns+1)*256/weight
    NQ:Never Queue
    
    LBLC:Locality-Based LC,動態的DH算法;
    LBLCR:LBLC with Replication,帶複製功能的LBLC;

lvs集羣的類型:

  • lvs-nat:修改請求報文的目標IP;多目標IP的DNAT;
  • lvs-dr:操縱封裝新的MAC地址;
  • lvs-tun:在原請求IP報文之外新加一個IP首部;
  • lvs-fullnat:修改請求報文的源和目標IP;

lvs-nat:
多目標IP的DNAT,通過將請求報文中的目標地址和目標端口修改爲某挑出的RS的RIP和PORT實現轉發;

    (1)RIP和DIP必須在同一個IP網絡,且應該使用私網地址;RS的網關要指向DIP;
    (2)請求報文和響應報文都必須經由Director轉發;Director易於成爲系統瓶頸;
    (3)支持端口映射,可修改請求報文的目標PORT;
    (4)vs必須是Linux系統,rs可以是任意系統;

lvs-dr:
通過爲請求報文重新封裝一個MAC首部進行轉發,源MAC是DIP所在的接口的MAC,目標MAC是某挑選出的RS的RIP所在接口的MAC地址;源IP/PORT,以及目標IP/PORT均保持不變;

Director和各RS都得配置使用VIP
(1) 確保前端路由器將目標IP爲VIP的請求報文發往Director:
    (a) 在前端網關做靜態綁定;
    (b) 在RS上使用arptables;
    (c) 在RS上修改內核參數以限制arp通告及應答級別;
        arp_announce
        arp_ignore
(2) RS的RIP可以使用私網地址,也可以是公網地址;RIP與DIP在同一IP網絡;RIP的網關不能指向DIP,以確保響應報文不會經由Director;
(3) RS跟Director要在同一個物理網絡;
(4) 請求報文要經由Director,但響應不能經由Director,而是由RS直接發往Client;
(5) 不支持端口映射;

lvs-tun:
轉發方式:不修改請求報文的IP首部(源IP爲CIP,目標IP爲VIP),而是在原IP報文之外再封裝一個IP首部(源IP是DIP,目標IP是RIP),將報文發往挑選出的目標RS;RS直接響應給客戶端(源IP是VIP,目標IP是CIP);

(1) DIP, VIP, RIP都應該是公網地址;
(2) RS的網關不能,也不可能指向DIP;
(3) 請求報文要經由Director,但響應不能經由Director;
(4) 不支持端口映射;
(5) RS的OS得支持隧道功能;

lvs-fullnat:
通過同時修改請求報文的源IP地址和目標IP地址進行轉發;

(1) VIP是公網地址,RIP和DIP是私網地址,且通常不在同一IP網絡;因此,RIP的網關一般不會指向DIP;
(2) RS收到的請求報文源地址是DIP,因此,只能響應給DIP;但Director還要將其發往Client;
(3) 請求和響應報文都經由Director;
(4) 支持端口映射;

注意:此類型默認不支持;

總結:

lvs-nat, lvs-fullnat:請求和響應報文都經由Director;
    lvs-nat:RIP的網關要指向DIP;
    lvs-fullnat:RIP和DIP未必在同一IP網絡,但要能通信;
lvs-dr, lvs-tun:請求報文要經由Director,但響應報文由RS直接發往Client;
    lvs-dr:通過封裝新的MAC首部實現,通過MAC網絡轉發;
    lvs-tun:通過在原IP報文之外封裝新的IP首部實現轉發,支持遠距離通信;

2、詳細描述nginx模塊並舉例說明

1、ngx_http_access_module模塊:
實現基於ip的訪問控制功能

        location / {
        allow 192.168.31.204/32;
        deny all;
        }

結果:

curl http://192.168.31.200
<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.12.2</center>
</body>
</html>

curl http://192.168.31.200
<h1>The node1 Server</h1>

2、ngx_http_auth_basic_module模塊
實現基於用戶的訪問控制,使用basic機制進行用戶認證;
注意:htpasswd命令由httpd-tools所提供;
語法:

  • auth_basic string | off;設置爲off可以不繼承上一級的basic配置
  • auth_basic_user_file file;指定保存用戶名密碼的文件

步驟:
創建用戶密碼文件,注意第一次創建加上-c以後就不需要加了,否則會覆蓋原來的文件。
方法1、htpasswd -cb /etc/nginx/conf.d/.htpasswd lvqing 123456
方法2、echo "lvqing:$(openssl passwd -crypt 123456)" >> /etc/nginx/conf.d/.htpasswd
再在配置文件中添加

location / {
    auth_basic           "admin passwd";
    auth_basic_user_file passwd/.htpasswd;
}

3、ngx_http_stub_status_module模塊
用於輸出nginx的基本狀態信息;
直接在配置文件中添加

location  /basic_status {
        stub_status;
}

結果:

curl http://192.168.31.200/basic_status
Active connections: 1
server accepts handled requests
 24 24 24
Reading: 0 Writing: 1 Waiting: 0

Active connections:當前狀態,活動狀態的連接數
accepts:統計總值,已經接受的客戶端請求的總數
handled:統計總值,已經處理完成的客戶端請求的總數
requests:統計總值,客戶端發來的總的請求數
Reading:當前狀態,正在讀取客戶端請求報文首部的連接的連接數
Writing:當前狀態,正在向客戶端發送響應報文過程中的連接數
Waiting:當前狀態,正在等待客戶端發出請求的空閒連接數

4、ngx_http_log_module模塊
用指定的格式寫入請求日誌
語法:
log_format name string ...; string可以使用nginx核心模塊及其它模塊內嵌的變量;

access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];訪問日誌文件路徑

  • access_log off;
  • buffer=size:緩衝大小
  • flush=time :日誌滾動的時間

open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
open_log_file_cache off;緩存日誌文件的元數據

  • max:緩存的最大文件描述符數量;
  • min_uses:在inactive指定的時長內訪問大於等於此值方可被當作活動項;
  • inactive:非活動時長;
  • valid:驗正緩存中各緩存項是否爲活動項的時間間隔;

示例:

'$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$gzip_ratio" "$http_x_forwarded_for"';

access_log  /var/log/nginx/logtest/nginx-access.log compression buffer=32k;

結果:

tail /var/log/nginx/logtest/nginx-access.log
192.168.31.204-lvqing[30/Dec/2018:11:59:41 +0800] "GET / HTTP/1.1" 200 262 "-" "curl/7.29.0" "-"
192.168.31.204-lvqing[30/Dec/2018:11:59:41 +0800] "GET / HTTP/1.1" 200 262 "-" "curl/7.29.0" "-"
192.168.31.205--[30/Dec/2018:11:59:01 +0800] "GET / HTTP/1.1" 200 262 "-" "curl/7.29.0" "-"
192.168.31.204-lvqing[30/Dec/2018:11:59:38 +0800] "GET / HTTP/1.1" 200 262 "-" "curl/7.29.0" "-"
192.168.31.204-lvqing[30/Dec/2018:11:59:39 +0800] "GET / HTTP/1.1" 200 262 "-" "curl/7.29.0" "-"
192.168.31.205--[30/Dec/2018:12:00:27 +0800] "GET / HTTP/1.1" 200 262 "-" "curl/7.29.0" "-"
192.168.31.205--[30/Dec/2018:12:00:27 +0800] "GET / HTTP/1.1" 200 262 "-" "curl/7.29.0" "-"
192.168.31.205--[30/Dec/2018:12:00:28 +0800] "GET / HTTP/1.1" 200 262 "-" "curl/7.29.0" "-"
192.168.31.205--[30/Dec/2018:11:58:59 +0800] "GET / HTTP/1.1" 200 262 "-" "curl/7.29.0" "-"
192.168.31.204-lvqing[30/Dec/2018:11:59:40 +0800] "GET / HTTP/1.1" 200 262 "-" "curl/7.29.0" "-"

5、ngx_http_gzip_module模塊
用gzip算法來壓縮數據可以節約帶寬,默認nginx不壓縮數據,但是壓縮會消耗CPU資源,且壓縮文本圖像類效果較好,能達到30%左右,但壓縮音頻視頻沒有多大意義,因爲本身音視頻就是被壓縮過的,很可能對音視頻壓縮反而會增大其體積。
語法:

1、gzip on | off;
        Enables or disables gzipping of responses.
                        
2、gzip_comp_level level;
        Sets a gzip compression level of a response. Acceptable values are in the range from 1 to 9.
                        
3、  gzip_disable regex ...;
        Disables gzipping of responses for requests with “User-Agent” header fields matching any of the specified regular expressions.
                        
4、  gzip_min_length length;
        啓用壓縮功能的響應報文大小閾值; 
                        
5、gzip_buffers number size;
        支持實現壓縮功能時爲其配置的緩衝區數量及每個緩存區的大小;
                        
6、gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...;
        nginx作爲代理服務器接收到從被代理服務器發送的響應報文後,在何種條件下啓用壓縮功能的;
            off:對代理的請求不啓用
            no-cache, no-store,private:表示從被代理服務器收到的響應報文首部的Cache-Control的值爲此三者中任何一個,則啓用壓縮功能;
                            
7、gzip_types mime-type ...;
        壓縮過濾器,僅對此處設定的MIME類型的內容啓用壓縮功能;

配置示例:

gzip  on;
gzip_comp_level 6;
gzip_min_length 64;
gzip_proxied any;
gzip_types text/xml text/css  application/javascript;   

結果:


13920922-68cbdd5aba7f3184.png
文本數據原來大小是465B壓縮後只有180B
13920922-b96e90dd5b38fd1a.png
而圖像壓縮比例更驚人

6、ngx_http_ssl_module模塊
啓用https時使用的模塊
語法:

1、ssl on | off;
    Enables the HTTPS protocol for the given virtual server.
                        
2、ssl_certificate file;
    當前虛擬主機使用PEM格式的證書文件;
                        
3、ssl_certificate_key file;
    當前虛擬主機上與其證書匹配的私鑰文件;
                        
4、ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];
    支持ssl協議版本,默認爲後三個;
                        
5、ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
    builtin[:size]:使用OpenSSL內建的緩存,此緩存爲每worker進程私有;
    [shared:name:size]:在各worker之間使用一個共享的緩存;
                        
6、ssl_session_timeout time;
    客戶端一側的連接可以複用ssl session cache中緩存 的ssl參數的有效時長;

當然因爲用到了ssl所以也需要CA服務器,可以將nginx服務器自己作CA簽發證書給自己和客戶端。
配置示例:

server{
        listen 443 ssl;
        server_name node1.lvqing.com;
        root /var/nginx/www/;
        access_log /var/log/nginx/ngx_ssl_access.log main;

        ssl on;
        ssl_certificate /etc/nginx/ssl/nginx.crt;
        ssl_certificate_key /etc/nginx/ssl/nginx.key;
        ssl_protocols sslv3 tlsv1 tlsv1.1 tlsv1.2;
        ssl_session_cache shared:SSL:10m; #打開會話緩存
}

7、ngx_http_rewrite_module模塊
重定向模塊,可以將客戶端的請求基於regex所描述的模式進行檢查,而後完成替換。當舊的業務和新的業務不一樣,網站更名了,就可以使用此模塊。將訪問舊的請求重定向成新的。
語法:

1、rewrite regex replacement [flag]
    將用戶請求的URI基於regex所描述的模式進行檢查,匹配到時將其替換爲replacement指定的新的URI;
    
    注意:如果在同一級配置塊中存在多個rewrite規則,那麼會自上而下逐個檢查;被某條件規則替換完成後,會重新一輪的替換檢查,因此,隱含有循環機制;[flag]所表示的標誌位用於控制此循環機制,但不超過10次;如果超過,會給客戶端一個500響應碼;
  redirect:臨時重定向,重寫完成後以臨時重定向方式直接返回重寫後生成的新URI給客戶端,由客戶端重新發起請求;不能以http://或https://開頭,使用相對路徑,狀態碼:302
  replacement:永久重定向是以http://或https://開頭,則替換結果會直接以重向返回給客戶端,狀態碼 :301

    [flag]:
        last:重寫完成後停止對當前URI在當前location中後續的其它重寫操作,而後對新的URI啓動新一輪重寫檢查;提前重啓新一輪循環; 
        break:重寫完成後停止對當前URI在當前location中後續的其它重寫操作,而後直接跳轉至重寫規則配置塊之後的其它配置;結束循環;
          last 和break是在服務器內部操作的,客戶端不知道,客戶端訪問的url不會發生變化。但是服務器端會返回替換過的新的內容。
        redirect:重寫完成後以臨時重定向方式直接返回重寫後生成的新URI給客戶端,由客戶端重新發起請求;不能以http://或https://開頭;
        permanent:重寫完成後以永久重定向方式直接返回重寫後生成的新URI給客戶端,由客戶端重新發起請求;
          redirect和permanent是服務器端給客戶端發一個301或者302的請求,客戶端需要重新發起請求,因此最終客戶端看到的瀏覽器是url和原始的url是不一樣的,url會被轉換新指定的。
2、return
    return code [text];
    return code URL;
    return URL;
    
    停止處理並將指定的代碼返回給客戶端。 
    
3、  rewrite_log on | off;
    是否開啓重寫日誌;
    
4、  if (condition) { ... }
    引入一個新的配置上下文 ;條件滿足時,執行配置塊中的配置指令;server, location;
    
    condition:
        比較操作符:
            ==
            !=
            ~:模式匹配,區分字符大小寫;
            ~*:模式匹配,不區分字符大小寫;
            !~:模式不匹配,區分字符大小寫;
            !~*:模式不匹配,不區分字符大小寫;
        文件及目錄存在性判斷:
            -e, !-e
            -f, !-f
            -d, !-d
            -x, !-x
            
5、set $variable value;
    用戶自定義變量 ;

示例:

rewrite /(.*)\.png$/$1.jpg;

將所有請求以png結尾的重定向以jpg結尾的

8、ngx_http_referer_module模塊
可以跟蹤鏈接從哪裏跳轉過來的,該字段可以用來防止盜鏈
語法:

valid_referers none | blocked | server_names | string ...;
    定義referer首部的合法可用值;
                    
        none:請求報文首部沒有referer首部;
        blocked:請求報文的referer首部沒有值;
        server_names:參數,其可以有值作爲主機名或主機名模式;
        arbitrary_string:直接字符串,但可使用*作通配符;
        regular expression:被指定的正則表達式模式匹配到的字符串;要使用~打頭,例如 ~.*\.lvqing\.com;

示例:

 valid_referers none block server_names *.lvqing.com *.lvqing.com *.lvqing.* ~.*\.lvqing\.com;
        if($invalid_referer) {
                return http://node1.lvqing.com/background.jpg;
        }
#定義如果出現無效的referer將返回code 403
#只用從匹配到的地址跳轉過來的請求才允許訪問return的地址

nginx的代理功能所使用到的模塊

9、ngx_http_headers_module模塊
向由代理服務器響應給客戶端的響應報文添加自定義首部,或修改指定首部的值
語法:

1、add_header name value [always];
    添加自定義首部;
    
    add_header X-Via  $server_addr;
    add_header X-Accel $server_name;
    
2、expires [modified] time;
    expires epoch | max | off;
    
    用於定義Expire或Cache-Control首部的值;

示例:

add_header proxy_name lvqing_proxy;
add_header lvqing_X-Via  $server_addr;
add_header lvqing_X-Accel  $server_name;

13920922-c6e51a77b88fed3b.png
image.png

10、ngx_http_proxy_module模塊
這個沒什麼好說的,沒這個nginx就無法代理轉發請求
語法:

1、proxy_pass URL;
    Context:    location, if in location, limit_except
    
    注意:proxy_pass後面的路徑不帶uri時,其會將location的uri傳遞給後端主機;
        
        server {
            ...
            server_name HOSTNAME;
            location /uri/ {
                proxy_pass  http://hos[:port];
            }
            ...
        }
        
        http://HOSTNAME/uri --> http://host/uri 
        
    proxy_pass後面的路徑是一個uri時,其會將location的uri替換爲proxy_pass的uri;
        
        server {
            ...
            server_name HOSTNAME;
            location /uri/ {
                proxy_pass http://host/new_uri/;
            }
            ...
        }
        
        http://HOSTNAME/uri/ --> http://host/new_uri/
        
    如果location定義其uri時使用了正則表達式的模式,或在if語句或limt_execept中使用proxy_pass指令,
則proxy_pass之後必須不能使用uri; 用戶請求時傳遞的uri將直接附加代理到的服務的之後;
    
        server {
            ...
            server_name HOSTNAME;
            location ~|~* /uri/ {
                proxy http://host;
            }
            ...
        }
        
        http://HOSTNAME/uri/ --> http://host/uri/;
        
2、proxy_set_header field value;
    設定發往後端主機的請求報文的請求首部的值;Context:   http, server, location
       proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        $proxy_add_x_forwarded_for:經過了哪些主機的代理使用,隔開
        $remote_addr:代表了客戶端的IP,可能是最後一個代理服務器的地址

3、proxy_cache_path
    定義可用於proxy功能的緩存;Context:    http            
    
    proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] 
[loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];
    

4、proxy_cache zone | off;
    指明要調用的緩存,或關閉緩存機制;Context:   http, server, location
    
5、  proxy_cache_key string;
    緩存中用於“鍵”的內容;
    
    默認值:proxy_cache_key $scheme$proxy_host$request_uri;
    
6、proxy_cache_valid [code ...] time;
    定義對特定響應碼的響應內容的緩存時長;
    
    定義在http{...}中;
    proxy_cache_path /var/cache/nginx/proxy_cache levels=1:1:1 keys_zone=pxycache:20m max_size=1g;
    
    定義在需要調用緩存功能的配置段,例如server{...}或location{....};
    proxy_cache pxycache;
    proxy_cache_key $request_uri;
    proxy_cache_valid 200 302 301 1h;    定義不同類的內容緩存多長時間
    proxy_cache_valid any 1m;
    
7、proxy_cache_use_stale
    
    proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off ...;
    
    Determines in which cases a stale cached response can be used when an error occurs during communication with the proxied server.
    
8、proxy_cache_methods GET | HEAD | POST ...;
    If the client request method is listed in this directive then the response will be cached. 
“GET” and “HEAD” methods are always added to the list, though it is recommended to specify them explicitly. 
    
9、proxy_hide_header field;
    By default, nginx does not pass the header fields “Date”, “Server”, “X-Pad”, and “X-Accel-...” 
from the response of a proxied server to a client. The proxy_hide_header directive sets additional fields that will not be passed.
    
10、proxy_connect_timeout time;
    Defines a timeout for establishing a connection with a proxied server. It should be noted that this timeout cannot usually exceed 75 seconds.
    建立鏈接服務器端超時
    默認爲60s;最長爲75s;
    
11、proxy_read_timeout time; 
    Defines a timeout for reading a response from the proxied server. The timeout is set only between two successive read operations, not for the transmission of the whole response.
    接收服務端響應超時
12、proxy_send_timeout time;
    Sets a timeout for transmitting a request to the proxied server. he timeout is set only between two successive write operations, 
not for the transmission of the whole request. If the proxied server does not receive anything within this time, the connection is closed.
    向服務端發請求超時           

示例:
所有發給node1以php結尾的請求都代理給後端的node2服務器,同時調用緩存pxycache,以proxy_host和request_uri做cache的建

proxy.conf
server{
        server_name node1.lvqing.com;
        location / {
        root /var/nginx/www/;
        }
        location ~* \.php$ {
                proxy_cache pxycache;
                proxy_cache_key $proxy_host$request_uri;
                proxy_pass http://node2.lvqing.com;
        }
}

nginx.conf
proxy_cache_path /var/cache/nginx/proxy_cache levels=1:1:1 keys_zone=pxycache:20m max_size=1g;

同時在node2的默認目錄下創建一個php測試文件
index.php
<h1>node2 Server</h2>
<?php
        phpinfo()
?>

結果:
成功代理到node2上

[root@node1 bak]# curl http://node1.lvqing.com/index.php
<h1>node2 Server</h2>
<?php
        phpinfo()
?>

11、ngx_http_fastcgi_module
該模塊允許將請求傳遞給FastCGI服務器。可以認爲這個模塊提供了nginx與web服務器上的應用交流的接口。有了這個模塊nginx就可以將請求轉發給web服務器上的php或者tomcat等應用程序,形成動態網站。
語法:


1、fastcgi_pass address;
    address爲fastcgi server的地址;  location, if in location;
    
        http://www.ilinux.io/admin/index.php --> /admin/index.php (uri)
            /data/application/admin/index.php
                
2、fastcgi_index name;
    fastcgi默認的主頁資源; 
    
3、fastcgi_param parameter value [if_not_empty];
    Sets a parameter that should be passed to the FastCGI server.
 The value can contain text, variables, and their combination.
    
        
4、fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] 
[loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];

    定義fastcgi的緩存;緩存位置爲磁盤上的文件系統,由path所指定路徑來定義;
    
        levels=levels:緩存目錄的層級數量,以及每一級的目錄數量;levels=ONE:TWO:THREE
            leves=1:2:2
        keys_zone=name:size
            k/v映射的內存空間的名稱及大小
        inactive=time
            非活動時長
        max_size=size
            磁盤上用於緩存數據的緩存空間上限

        
5、fastcgi_cache zone | off;
    調用指定的緩存空間來緩存數據;http, server, location
    
6、fastcgi_cache_key string;
    定義用作緩存項的key的字符串;
    
7、fastcgi_cache_methods GET | HEAD | POST ...;
    爲哪些請求方法使用緩存;
    
8、fastcgi_cache_min_uses number;
    緩存空間中的緩存項在inactive定義的非活動時間內至少要被訪問到此處所指定的次數方可被認作活動項;
    
9、fastcgi_cache_valid [code ...] time;
    不同的響應碼各自的緩存時長;
    
10、fastcgi_keep_conn on | off;
        By default, a FastCGI server will close a connection right after sending the response. However, when this directive is set to the value on, nginx will instruct a FastCGI server to keep connections open.
        默認情況下,FastCGI服務器會在發送響應後立即關閉連接。然而,當這個指令被設置爲on時,nginx會指示FastCGI服務器保持連接打開。

示例:
node2配置文件

fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2:1 keys_zone=fcgi:20m inactive=120s;

server{
        server_name node2.lvqing.com;
        location ~* \.php$ {
                root /var/nginx/www;
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                #這裏的$document_root指的是上面root指定的家目錄,意在解釋這個目錄內的php腳本。
                include        fastcgi_params;
                fastcgi_cache fcgi;
                fastcgi_cache_key $request_uri;
                fastcgi_cache_valid 200 302 10m;
                fastcgi_cache_valid 301 1h;
                fastcgi_cache_valid any 1m;
        }
}

結果

13920922-b23b0f18b1066b6c.png

12、ngx_http_upstream_module
將後端的多個服務器定義成服務器組,對代理的請求做基於七層的負載均衡,自帶健康狀態檢測功能,可由proxy_pass,fastcgi_pass,uwsgi_pass,scgi_pass和memcached_pass指令引用的服務器組
負載均衡設備如果要根據真正的應用層內容再選擇服務器,只能先代理最終的服務器和客戶端建立連接(三次握手)後,才能看到客戶端發送的真正應用層內容的報文,然後再根據該報文中的特定字段,再加上負載均衡設備設置的服務器選擇方式,決定最終選擇的內部服務器。負載均衡設備在這種情況下,更類似於一個代理服務器。負載均衡和前端的客戶端以及後端的服務器會分別建立TCP連接。所以從這個技術原理上來看,七層負載均衡明顯的對負載均衡設備的要求更高,處理七層的能力也必然會低於四層模式的部署方式。
語法:

1、upstream name { ... }
    定義後端服務器組,會引入一個新的上下文;Context: http
    
    upstream httpdsrvs {
        server ...
        server...
        ...
    }
    
2、server address [parameters];
    在upstream上下文中server成員,以及相關的參數;Context:  upstream
    
    address的表示格式:
        unix:/PATH/TO/SOME_SOCK_FILE
        IP[:PORT]
        HOSTNAME[:PORT]
        
    parameters:
        weight=number
            權重,默認爲1;
        max_fails=number
            失敗嘗試最大次數;超出此處指定的次數時,server將被標記爲不可用;
        fail_timeout=time
            設置將服務器標記爲不可用狀態的超時時長;
        max_conns
            當前的服務器的最大併發連接數;
        backup
            將服務器標記爲“備用”,即所有服務器均不可用時此服務器才啓用;
        down
            標記爲“不可用”;
            
3、least_conn;
    最少連接調度算法,當server擁有不同的權重時其爲wlc;
    
4、  ip_hash;
    源地址hash調度方法;類似lvs的sh算法,使用了就不能使用backup了
    
5、hash key [consistent];
    基於指定的key的hash表來實現對請求的調度,此處的key可以直接文本、變量或二者的組合;
    
    作用:將請求分類,同一類請求將發往同一個upstream server;
    
    If the consistent parameter is specified the ketama consistent hashing method will be used instead.
        

    示例:
        hash $request_uri consistent;
        這是根據請求的資源進行會話粘性,在代理服務器上都有一張hash表記錄一切
        帶consistent指定一致性哈希自帶虛擬節點,就算後端節點失效了也能重新調度
        hash $remote_addr;
        hash $cookie_name

6、keepalive connections;
    爲每個worker進程保留的空閒的長連接數量;
    爲服務器端保持長鏈接,不需要一個併發訪問就打開一個套接字端口

7、least_time header | last_byte;
    最短平均響應時長和最少連接;
    header:response_header; 
    last_byte: full_response; 
    
    僅Nginx Plus有效;
    
8、 health_check [parameters];
    定義對後端主機的健康狀態檢測機制;只能用於location上下文;
    
    可用參數:
        interval=time:檢測頻率,默認爲每隔5秒鐘;
        fails=number:判斷服務器狀態轉爲失敗需要檢測的次數;
        passes=number:判斷服務器狀態轉爲成功需要檢測的次數;
        uri=uri:判斷其健康與否時使用的uri;
        match=name:基於指定的match來衡量檢測結果的成敗;
        port=number:使用獨立的端口進行檢測;
        
    僅Nginx Plus有效;
        
9、 match name { ... }
    Defines the named test set used to verify responses to health check requests.
    定義衡量某檢測結果是否爲成功的衡量機制;
    
    專用指令:
        status:期望的響應碼;
            status CODE
            status ! CODE
            ...
        header:基於響應報文的首部進行判斷
            header HEADER=VALUE
            header HEADER ~ VALUE 
            ...
        body:基於響應報文的內容進行判斷
            body ~ "PATTERN"
            body !~ "PATTERN"
            
    僅Nginx Plus有效;

示例:
在node1代理服務器上定義一個httpdsrvs組,七層負載均衡,基於uri的hash以保存會話粘性

    upstream httpdsrvs{
        hash $request_uri consistent;
        server node2.lvqing.com weight=2;
        server node3.lvqing.com weight=1  max_fails=3 fail_timeout=30s;
    }

    location / {
        proxy_cache pxycache;
        proxy_cache_key $proxy_host$request_uri;
        proxy_pass httpdsrvs;
    }

結果:
因爲我們前面基於uri做了會話粘性,相同的請求都會發給後端的同一臺服務器所以這裏只有一臺響應。當然如果node2掛掉會自動切換到node3

for i in {1..10};do curl http://node1.lvqing.com;done
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>

如果將上面的 hash $request_uri consistent;去掉會是一下的結果

for i in {1..10};do curl http://node1.lvqing.com;done
<h1>node2 Server</h1>
<h1>node3 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node3 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node3 Server</h1>
<h1>node3 Server</h1>

這是基於7層代理的,效率相對四層來說較低,但我們可以對請求做的操作也更多
13、ngx_stream_core_module
模擬反代基於tcp或udp的服務連接,即工作於傳輸層的反代或調度器,工作在四層的代理。
語法:
負載均衡設備在接收到第一個來自客戶端的SYN 請求時,即通過上述方式選擇一個最佳的服務器,並對報文中目標IP地址進行修改(改爲後端服務器IP),直接轉發給該服務器。TCP的連接建立,即三次握手是客戶端和服務器直接建立的,負載均衡設備只是起到一個類似路由器的轉發動作。在某些部署情況下,爲保證服務器回包可以正確返回給負載均衡設備,在轉發報文的同時可能還會對報文原來的源地址進行修改。

1、stream { ... }
定義stream相關的服務;Context:main

2、listen
listen address:port [ssl] [udp] [proxy_protocol] [backlog=number] [bind] [ipv6only=on|off] 
[reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
監聽的端口;
    默認爲tcp協議;
    udp: 監聽udp協議的端口;

14、ngx_stream_proxy_module
在stream裏使用的proxy語句,與stream配套使用
語法:

(1) proxy_pass address;
    Sets the address of a proxied server. The address can be specified as a domain name or IP address, and a port or as a UNIX-domain socket path.
    
(2) proxy_timeout timeout;
    Sets the timeout between two successive read or write operations on client or proxied server connections. If no data is transmitted within this time, the connection is closed.
    默認爲10m; 
    
(3) proxy_connect_timeout time;
    Defines a timeout for establishing a connection with a proxied server.  
    設置nginx與被代理的服務器嘗試建立連接的超時時長;默認爲60s;

示例:

stream {
    upstream nginxsrvs {
        server 192.168.31.201:80; 
        server 192.168.31.203:80; 
        least_conn;
    }

    server {
        listen 192.168.31.200:8080;
        proxy_pass nginxsrvs;
        proxy_timeout 60s;
        proxy_connect_timeout 10s;
    }
}   

結果:

 for i in {1..10};do curl http://192.168.31.200:8080;done
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node3 Server</h1>
<h1>node3 Server</h1>
<h1>node2 Server</h1>
<h1>node2 Server</h1>
<h1>node3 Server</h1>
<h1>node2 Server</h1>
<h1>node3 Server</h1>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章