歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> 【nginx】負載均衡和proxy的配置

【nginx】負載均衡和proxy的配置

日期:2017/3/1 12:20:41   编辑:關於Linux
使用upstream模塊實現nginx負載均衡 使用nginx_upstream_check_module模塊實現後端服務器的健康檢查 使用nginx-sticky-module擴展模塊實現Cookie會話黏貼(session-sticky效果) 使用proxy模塊實現靜態文件緩存 使用ngx_cache_purge實現更強大的緩存清除功能 1. nginx-sticky-module 這個模塊的作用是通過cookie的方式將來自同一個客戶端(浏覽器)的請求發送到同一個後端服務器上處理,這樣一定程度上可以解決多個backend servers的session同步的問題 —— 因為不再需要同步,而RR輪詢模式必須要運維人員自己考慮session同步的實現。 另外內置的 ip_hash 也可以實現根據客戶端IP來分發請求,但它很容易造成負載不均衡的情況,而如果nginx前面有CDN網絡或者來自同一局域網的訪問,它接收的客戶端IP是一樣的,容易造成負載不均衡現象。淘寶Tengine的 ngx_http_upstream_session_sticky_module 也是類似的功能。nginx-sticky-module的cookie過期時間,默認浏覽器關閉就過期,也就是會話方式。 這個模塊並不合適不支持 Cookie 或手動禁用了cookie的浏覽器,此時默認sticky就會切換成RR。它不能與ip_hash同時使用。 原理其實很簡單,當一個客戶端請求過來時,會 set-cookie 一個 cookie 來標注本次請求的服務器(第一次是隨機).然後下次請求都會包含這個 cookie .然後就能很好的區分原本請求的服務器了.我測試過,當默認請求的後端服務器死掉後,會還是會自動切換的.另外,這個模塊並不合適對不支持 Cookie 的浏覽器 Sticky module is based on a "best effort" algorithm. Its aim is not to handle security somehow. It's been made to ensure that normal users are always redirected to the same backend server: that's all! sticky安裝 ./configure ... --add-module=/absolute/path/to/nginx-sticky-module-ng make make install sticky配置 upstream { sticky; server 127.0.0.1:9000; server 127.0.0.1:9001; server 127.0.0.1:9002; } sticky [name=route] [domain=.foo.bar] [path=/] [expires=1h] [hash=index|md5|sha1] [no_fallback] [secure] [httponly]; name: the name of the cookies used to track the persistant upstream srv; default: route domain: the domain in which the cookie will be valid default: nothing. Let the browser handle this. path: the path in which the cookie will be valid default: / expires: the validity duration of the cookie default: nothing. It's a session cookie. restriction: must be a duration greater than one second hash: the hash mechanism to encode upstream server. It cant' be used with hmac. default: md5hmac: the HMAC hash mechanism to encode upstream server It's like the hash mechanism but it uses hmac_key to secure the hashing. It can't be used with hash. md5|sha1: well known hash default: none. see hash. md5|sha1: well known hash index: it's not hashed, an in-memory index is used instead, it's quicker and the overhead is shorter Warning: the matching against upstream servers list is inconsistent. So, at reload, if upstreams servers has changed, index values are not guaranted to correspond to the same server as before! USE IT WITH CAUTION and only if you need to! hmac_key: the key to use with hmac. It's mandatory when hmac is set default: nothing. no_fallback: when this flag is set, nginx will return a 502 (Bad Gateway or Proxy Error) if a request comes with a cookie and the corresponding backend is unavailable. secure enable secure cookies; transferred only via https httponly enable cookies not to be leaked via js 官方文檔也有個 sticky 指令,作用幾乎是一樣的,但這是nginx商業版本裡才有的特性。包括後面的check指令,在nginx的商業版本裡也有對應的health_check(配在 location )實現幾乎一樣的監控檢查功能。 2、nginx負載均衡 輪詢(默認) : 每個請求按時間順序逐一分配到不同的後端服務器,如果後端某台服務器宕機,故障系統被自動剔除,使用戶訪問不受影響。Weight 指定輪詢權值,Weight值越大,分配到的訪問機率越高,主要用於後端每個服務器性能不均的情況下。 ip_hash : 每個請求按訪問IP的hash結果分配,這樣來自同一個IP的訪客固定訪問一個後端服務器,有效解決了動態網頁存在的session共享問題。當然如果這個節點不可用了,會發到下個節點,而此時沒有session同步的話就注銷掉了。 least_conn : 請求被發送到當前活躍連接最少的realserver上。會考慮weight的值。 url_hash : 此方法按訪問url的hash結果來分配請求,使每個url定向到同一個後端服務器,可以進一步提高後端緩存服務器的效率。Nginx本身是不支持url_hash的,如果需要使用這種調度算法,必須安裝nginx 的hash軟件包 nginx_upstream_hash 。 fair : 這是比上面兩個更加智能的負載均衡算法。此種算法可以依據頁面大小和加載時間長短智能地進行負載均衡,也就是根據後端服務器的響應時間來分配請求,響應時間短的優先分配。Nginx本身是不支持fair的,如果需要使用這種調度算法,必須下載Nginx的 upstream_fair 模塊。 ip_hash的配置
upstream backend {
    ip_hash;
    server 192.168.1.225:8080 weight 2;
    server 192.168.1.226:8080 weight=1 max_fails=2 fail_timeout=30s ;
    server 192.168.1.227:8080 backup;
}
server {
    location / {
        proxy_pass http://backend;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
    }
}

weight:輪詢權值也是可以用在ip_hash的,默認值為1 max_fails:允許請求失敗的次數,默認為1。當超過最大次數時,返回proxy_next_upstream 模塊定義的錯誤。 fail_timeout:有兩層含義,一是在 30s 時間內最多容許 2 次失敗;二是在經歷了 2 次失敗以後,30s時間內不分配請求到這台服務器。 backup:備份機器。當其他所有的非backup機器出現故障的時候,才會請求backup機器 max_conns: 限制同時連接到某台後端服務器的連接數,默認為0即無限制。因為queue指令是commercial,所以還是保持默認吧。 proxy_next_upstream:這個指令屬於 http_proxy 模塊的,指定後端返回什麼樣的異常響應時,使用另一個realserver 項目地址: https://bitbucket.org/nginx-goodies/nginx-sticky-module-ng https://code.google.com/p/nginx-sticky-module/ 3、 upstream_check nginx自帶是沒有針對負載均衡後端節點的健康檢查的,但是可以通過默認自帶的 ngx_http_proxy_module 模塊和 ngx_http_upstream_module 模塊中的相關指令來完成當後端節點出現故障時,自動切換到下一個節點來提供訪問。 nginx_upstream_check_module 是專門提供負載均衡器內節點的健康檢查的外部模塊,由淘寶工程師開發,通過它可以用來檢測後端 realserver 的健康狀態。如果後端 realserver 不可用,則後面的請求就不會轉發到該節點上,並持續檢查幾點的狀態。在淘寶自己的 tengine 上是自帶了該模塊。
upstream backend {
    sticky;
    server 192.168.1.225:8080 weight=2;
    server 192.168.1.226:8081 weight=1 max_fails=2 fail_timeout=30s ;
    server 192.168.1.227:8080 weight=1 max_fails=2 fail_timeout=30s ;
    server 192.168.1.227:8081;
      
    check interval=5000 rise=2 fall=3 timeout=1000 type=http;
    check_http_send "HEAD / HTTP/1.0\r\n\r\n";
    check_http_expect_alive http_2xx http_3xx;
}
server {
    location / {
        proxy_pass http://backend;
    }
    location /status {
        check_status;
        access_log off;
        allow 192.168.1.0/24;
        deny all;
    }
}

nginx_upstream_check_module 對name這個負載均衡條目中的所有節點,每個5秒檢測一次,請求2次正常則標記 realserver狀態為up,如果檢測 3 次都失敗,則標記 realserver的狀態為down,超時時間為1秒。check指令只能出現在upstream中: interval : 向後端發送的健康檢查包的間隔。 fall : 如果連續失敗次數達到fall_count,服務器就被認為是down。 rise : 如果連續成功次數達到rise_count,服務器就被認為是up。 timeout : 後端健康請求的超時時間。 default_down : 設定初始時服務器的狀態,也就是一開始服務器認為是不可用,要等健康檢查包達到一定成功次數以後才會被認為是健康的。 type:健康檢查包的類型,現在支持以下多種類型 tcp:簡單的tcp連接,如果連接成功,就說明後端正常。 http:發送HTTP請求,通過後端的回復包的狀態來判斷後端是否存活。 ajp:向後端發送AJP協議的Cping包,通過接收Cpong包來判斷後端是否存活。 ssl_hello:發送一個初始的SSL hello包並接受服務器的SSL hello包。 mysql: 向mysql服務器連接,通過接收服務器的greeting包來判斷後端是否存活。 fastcgi:發送一個fastcgi請求,通過接受解析fastcgi響應來判斷後端是否存活 port: 指定後端服務器的檢查端口。你可以指定不同於真實服務的後端服務器的端口,比如後端提供的是443端口的應用,你可以去檢查80端口的狀態來判斷後端健康狀況。默認是0,表示跟後端server提供真實服務的端口一樣。該選項出現於Tengine-1.4.0。 如果 type 為 http ,你還可以使用check_http_send來配置http監控檢查包發送的請求內容,為了減少傳輸數據量,推薦采用 HEAD 方法。當采用長連接進行健康檢查時,需在該指令中添加keep-alive請求頭,如: HEAD / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n 。當采用 GET 方法的情況下,請求uri的size不宜過大,確保可以在1個interval內傳輸完成,否則會被健康檢查模塊視為後端服務器或網絡異常。 check_http_expect_alive 指定HTTP回復的成功狀態,默認認為 2XX 和 3XX 的狀態是健康的。 項目地址:https://github.com/yaoweibin/nginx_upstream_check_module 。 4、 proxy緩存的使用 緩存配置如下
http {
    proxy_temp_path /usr/local/nginx-1.6/proxy_temp;
    proxy_cache_path /usr/local/nginx-1.6/proxy_cache levels=1:2 keys_zone=cache_one:100m inactive=2d max_size=2g;
      
    server {


        location ~ .*\.(gif|jpg|png|html|css|js|ico|swf|pdf)(.*) {
            proxy_pass http://backend;
            proxy_redirect off;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              
            proxy_cache cache_one;
            add_header Nginx-Cache $upstream_cache_status;
            proxy_cache_valid 200 304 301 302 8h;
            proxy_cache_valid 404 1m;
            proxy_cache_valid any 2d;
            proxy_cache_key $host$uri$is_args$args;
            expires 30d;
        }

        location ~ /purge(/.*) {
            allow 127.0.0.1;
            allow 192.168.1.0/24;
            deny all;
            proxy_cache_purge cache_one $host$1$is_args$args;
            error_page 405 =200 /purge$1;
        }
    }
}

清除緩存 上述配置的proxy_cache_purge指令用於方便的清除緩存,需要ngx_cache_purge 模塊 echo -e 'PURGE / HTTP/1.0\r\n' | nc http:/example.com/purge/path echo -e 'GET /purge/ HTTP/1.0\r\n' | nc http:/example.com/purge/path
Copyright © Linux教程網 All Rights Reserved