使用nginx做負載均衡的模塊解讀
使用nginx做負載均衡的兩大模塊:
- upstream 定義負載節(jié)點池。
- location 模塊 進行URL匹配。
- proxy模塊 發(fā)送請求給upstream定義的節(jié)點池。
upstream模塊解讀
nginx 的負載均衡功能依賴于 ngx_http_upstream_module模塊,所支持的代理方式有 proxy_pass(一般用于反向代理),fastcgi_pass(一般用于和動態(tài)程序交互),memcached_pass,proxy_next_upstream,fastcgi_next_pass,memcached_next_pass 。
upstream 模塊應該放于http{}標簽內(nèi)。
模塊寫法:
upstream backend { ip_hash; server backend1.example.com weight=5; server backend2.example.com:8080; server backup1.example.com:8080 backup; server backup2.example.com:8080 backup; }
實例一:
upstream dynamic { zone upstream_dynamic 64k; server backend1.example.com weight=5; server backend2.example.com:8080 fail_timeout=5s slow_start=30s; server 192.0.2.1 max_fails=3; server backend3.example.com resolve; server backup1.example.com:8080 backup; server backup2.example.com:8080 backup; }
語法解釋:
nginx默認支持四種調(diào)度算法
- 輪詢(rr),每個請求按時間順序逐一分配到不同的后端服務器,如果后端服務器故障,故障系統(tǒng)自動清除,使用戶訪問不受影響。
- 輪詢權(quán)值(weight),weight值越大,分配到的訪問幾率越高,主要用于后端每個服務器性能不均的情況。
- ip_hash,每個請求按訪問IP的hash結(jié)果分配,這樣來自同一個IP的固定訪問一個后端服務器,主要解決動態(tài)網(wǎng)站session共享的問題。
- url_hash,按照訪問的URL的hash結(jié)果來分配請求,是每個URL定向到同一個后端服務器,可以進一步提高后端緩存服務器的效率,nginx本身不支持,如果想使用需要安裝nginx的hash軟件包。
- fair,這個算法可以依據(jù)頁面大小和加載時間長短智能的進行負載均衡,也就是根據(jù)后端服務器的響應時間來分配請求,相應時間短的優(yōu)先分配,默認不支持,如果想使用需要安裝upstream_fail模塊。
- least_conn 最少鏈接數(shù),那個機器連接數(shù)少就分發(fā)。
server模塊的寫法
server IP 調(diào)度狀態(tài)
server指令指定后端服務器IP地址和端口,同時還可以設定每個后端服務器在負載均衡調(diào)度中的狀態(tài)。
- down 表示當前的server暫時不參與負載均衡。
- backup 預留的備份服務器,當其他所有的非backup服務器出現(xiàn)故障或者忙的時候,才會請求backup機器,因為這臺集群的壓力最小。
- max_fails 允許請求失敗的次數(shù),默認是1,當超過最大次數(shù)時,返回proxy_next_upstream模塊定義的錯誤。0表示禁止失敗嘗試,企業(yè)場景:2-3.京東1次,藍汛10次,根據(jù)業(yè)務需求去配置。
fail_timeout,在經(jīng)歷了max_fails次失敗后,暫停服務的時間。京東是3s,藍汛是3s,根據(jù)業(yè)務需求配置。常規(guī)業(yè)務2-3秒合理。
例:如果max_fails是5,他就檢測5次,如果五次都是502.那么,他就會根據(jù)fail_timeout 的值,等待10秒,再去檢測。
server 如果接域名,需要內(nèi)網(wǎng)有DNS服務器,或者在負載均衡器的hosts文件做域名解析。server后面還可以直接接IP或IP加端口。
長連接 keepalive
upstream backend { server backend2.example.com:8080; server backup1.example.com:8080 backup; keepalive 100; }
通過該指令配置了每個worker進程與上游服務器可緩存的空閑連接的最大數(shù)量。
當超出這個數(shù)量時,最近最少使用的連接將被關(guān)閉。keepalive指令不限制worker進程與上游服務器的總連接。
location / { # 支持keep-alive proxy_http_version 1.1; proxy_set_header Connection ""; proxy_pass http://backup; }
- 如果是http/1.0 需要配置發(fā)送"Connection: Keep-Alive" 請求頭。
- 上游服務器不要忘記開啟長連接支持。
連接池配置建議
- 總長連接數(shù)是"空閑連接池"+"釋放連接池"的長連接總數(shù)。
- 首先,長連接配置不會限制worker進程可以打開的總連接數(shù)(超了的作為短連接)。另外連接池一定要根據(jù)場景合理進行設置。
空閑連接池太小,連接不夠用,需要不斷建連接。
空閑連接池太大,空閑連接太多,還沒使用就超時。
建議只對小報文開啟長連接。
location 模塊解讀
location作用:基于一個指令設置URI。
基本語法:
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... } location @name { ... } Default: — Context: server, location
- = 精確匹配,如果找到匹配=號的內(nèi)容,立即停止搜索,并立即處理請求(優(yōu)先級最高)
- ~ 區(qū)分大小寫
- ~* 不區(qū)分大小寫
- ^~ 只匹配字符串,不匹配正則表達式
- @ 指定一個命名的location,一般用于內(nèi)部重定義請求,location @name {…}
匹配是有優(yōu)先級的,不是按照nginx的配置文件進行。
官方的例子:
location = / { [ configuration A ] } location / { [ configuration B ] } location /documents/ { [ configuration C ] } location ^~ /images/ { [ configuration D ] } location ~* \.(gif|jpg|jpeg)$ { [ configuration E ] }
結(jié)論:
- / 匹配A。
- /index.html 匹配B
- /documents/document.html 匹配C
- /images/1.gif 匹配D
- /documents/1.jpg 匹配的是E。
測試用的例子:
location / { return 401; } location = / { return 402; } location /documents/ { return 403; } location ^~ /images/ { return 404; } location ~* \.(gif|jpg|jpeg)$ { return 500; }
測試結(jié)果(重點看):
[root@lb01 conf]# curl -I -s -o /dev/null -w "%{http_code}\n" http://10.0.0.7/ 402 [root@lb01 conf]# curl -I -s -o /dev/null -w "%{http_code}\n" http://10.0.0.7/index.html 401 [root@lb01 conf]# curl -I -s -o /dev/null -w "%{http_code}\n" http://10.0.0.7/documents/document.html 403 [root@lb01 conf]# curl -I -s -o /dev/null -w "%{http_code}\n" http://10.0.0.7/images/1.gif 404 [root@lb01 conf]# curl -I -s -o /dev/null -w "%{http_code}\n" http://10.0.0.7/dddd/1.gif 500
結(jié)果總結(jié):
匹配的優(yōu)先順序,=>^~(匹配固定字符串,忽略正則)>完全相等>~*>空>/ 。
工作中盡量將'='放在前面
proxy_pass 模塊解讀
proxy_pass 指令屬于ngx_http_proxy_module 模塊,此模塊可以將請求轉(zhuǎn)發(fā)到另一臺服務器。
寫法:
proxy_pass http://localhost:8000/uri/;
實例一:
upstream blog_real_servers { server 10.0.0.9:80 weight=5; server 10.0.0.10:80 weight=10; server 10.0.0.19:82 weight=15; } server { listen 80; server_name blog.etiantian.org; location / { proxy_pass http://blog_real_servers; proxy_set_header host $host; } }
- proxy_set_header:當后端Web服務器上也配置有多個虛擬主機時,需要用該Header來區(qū)分反向代理哪個主機名,proxy_set_header host $host;。
- proxy_set_header X-Forwarded-For :如果后端Web服務器上的程序需要獲取用戶IP,從該Header頭獲取。proxy_set_header X-Forwarded-For $remote_addr;
配置后端服務器接收前端真實IP
配置如下:
log_format commonlog '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_age
rs_apache節(jié)點的httpd.conf配置
LogFormat "\"%{X-Forwarded-For}i\" %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{U ser-Agent}i\"" combined修改日志記錄 apache LogFormat "\"%{X-Forwarded-For}i\" %l %u %t \"%r\" %>s %b" common
proxy_pass相關(guān)的優(yōu)化參數(shù)
- client_max_body_size 10m; 允許客戶端請求的最大的單個文件字節(jié)數(shù)。
- client_body_buffer_size 128k; 緩沖區(qū)代理緩沖用戶端請求的最大字節(jié)數(shù) 可以理解為先保存到本地再傳給用戶。
- proxy_connect_timeout 600; 跟后端服務器連接的超時時間_發(fā)起握手等候響應超時時間。
- proxy_read_timeout 600; 連接成功后_等候后端服務器響應時間_其實已經(jīng)進入后端的排隊之中等候處理。
- proxy_send_timeout 600; 后端服務器回傳數(shù)據(jù)時間,就是在規(guī)定時間之內(nèi)后端服務器必須傳完所有的數(shù)據(jù)。
- proxy_buffer_size 8k; 代理請求緩存區(qū),這個緩存區(qū)間會保存用戶的頭信息以供Nginx進行規(guī)則處理,一般只要設置能保存下頭信息即可。
- proxy_buffers 4 32k; 同上 告訴Nginx保存單個頁面使用的空間大小,假設網(wǎng)頁大小平均在32k以下的話。
- proxy_busy_buffers_size 64k; 如果系統(tǒng)很忙的時候可以申請更大的proxy_buffers 官方推薦(proxy_buffers*2)。
- proxy_max_temp_file_size 1024m; 當 proxy_buffers 放不下后端服務器的響應內(nèi)容時,會將一部分保存到硬盤的臨時文件中,這個值用來設置最大臨時文件大小,默認1024M,它與 proxy_cache 沒有關(guān)系。大于這個值,將從upstream服務器傳回。設置為0禁用。
- proxy_temp_file_write_size 64k; proxy緩存臨時文件的大小 proxy_temp_path(可以在編譯的時候)指定寫到哪那個目錄。
健康檢查
Nginx提供了health_check語句來提供負載(upstream)時的鍵康檢查機制(注意:此語句需要設置在location上下文中)。
支持的參數(shù)有:
- interval=time:設置兩次健康檢查之間的間隔值,默認為5秒
- fails=number:設置將服務器視為不健康的連續(xù)檢查次數(shù),默認為1次
- passes=number:設置一個服務器被視為健康的連續(xù)檢查次數(shù),默認為1次
- uri=uri:定義健康檢查的請求URI,默認為”/“
- match=name:指定匹配配置塊的名字,用記測試響應是否通過健康檢測。默認為測試返回狀態(tài)碼為2xx和3xx
一個簡單的設置如下,將使用默認值:
location / { proxy_pass http://backend; health_check; }
對就應用,我們可以專門定義一個API用于健康檢查:/api/health_check,并只返回HTTP狀態(tài)碼為200。并設置兩次檢查之間的間隔值為1秒。這樣,health_check語句的配置如下:
health_check uri="/api/health_check" interval;
匹配match的方法
http { server { ... location / { proxy_pass http://backend; health_check match=welcome; } } match welcome { status 200; header Content-Type = text/html; body ~ "Welcome to nginx!"; } }
match 例子舉例
- status 200;: status 等于 200
- status ! 500;: status 不是 500
- status 200 204;: status 是 200 或 204
- status ! 301 302;: status 不是301或302。
- status 200-399;: status 在 200 到 399之間。
- status ! 400-599;: status 不在 400 到 599之間。
- status 301-303 307;: status 是 301, 302, 303, 或 307。
- header Content-Type = text/html;: “Content-Type” 得值是 text/html。
- header Content-Type != text/html;: “Content-Type” 不是 text/html。
- header Connection ~ close;: “Connection” 包含 close。
- header Connection !~ close;: “Connection” 不包含 close。
- header Host;: 請求頭包含 “Host”。
- header ! X-Accel-Redirect;: 請求頭不包含 “X-Accel-Redirect”。
- body ~ "Welcome to nginx!";: body 包含 “Welcome to nginx!”。
- body !~ "Welcome to nginx!";: body 不包含 “Welcome to nginx!”。
一個完整的nginx實例
[root@lb01 conf]# cat nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; #blog lb by oldboy at 201303 upstream blog_real_servers { server 10.0.0.9:80 weight=1 max_fails=1 fail_timeout=10s; server 10.0.0.10:80 weight=1 max_fails=2 fail_timeout=20s; } server { listen 80; server_name blog.etiantian.org; location / { proxy_pass http://blog_real_servers; include proxy.conf; } } } [root@lb01 conf]# cat proxy.conf proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k;
擴展補充
只允許使用GET,HEAD,POST方法去請求
## Only allow these request methods ## if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; }
實戰(zhàn)
根據(jù)URI及l(fā)ocation實現(xiàn)動靜分離。
最終實現(xiàn):
- /static/的URL都去訪問10.0.0.9。
- /dynamic/的URL都去訪問10.0.0.10。
- 圖片這些靜態(tài)文件去訪問10.0.0.9。
- /upload/的URL都去訪問10.0.0.10。
[root@lb01 conf]# cat nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; #blog lb by oldboy at 201303 upstream static_pools { server 10.0.0.9:80; } upstream dynamic_pools { server 10.0.0.10:80; } upstream upload_pools { server 10.0.0.9:80; } server { listen 80; server_name blog.biglittleant.cn; location / { proxy_pass http://static_pools; include proxy.conf; } location /static/ { proxy_pass http://static_pools; include proxy.conf; } location ~* \.(gif|jpg|jpeg)$ { proxy_pass http://static_pools; include proxy.conf; } location /dynamic/ { proxy_pass http://dynamic_pools; include proxy.conf; } location /upload/ { proxy_pass http://upload_pools; include proxy.conf; } } }
實現(xiàn)蘋果手機和安卓手機訪問不同的地址
server { listen 80; server_name blog.etiantian.org; location / { if ($http_user_agent ~* "android") { proxy_pass http://android_pools; } if ($http_user_agent ~* "iphone") { proxy_pass http://iphone_pools; } proxy_pass http://pc_pools; include extra/proxy.conf; } access_log off; }
參考文檔
nginx-proxy_pass官網(wǎng)
到此這篇關(guān)于使用nginx做負載均衡的模塊解讀的文章就介紹到這了,更多相關(guān)nginx 負載均衡內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。