nginx官方網站:http://nginx.org/
1. Nginx連接后端的方式:反向代理(proxy_pass)、直連fastcgi(fastcgi_pass)
例子:
fastcgi_pass backend1;
proxy_pass http://backend2;
location塊中配置此項,表示用反向代理或直連fastcgi的方式連接后端服務,其中backend1、backend2為upstream配置,其中配置下游的ip&port列表和調度參數,見下文。
注意:fastcgi_pass與proxy_pass是互斥配置,不能同時生效。
2. Nginx調度與負載均衡配置(upstream配置)
例如:
upstream bakend {
server 192.168.0.14 weight=10;
server 192.168.0.15 weight=10;
upstream bakend {
ip_hash;
server 192.168.0.14:88;
server 192.168.0.15:80;
server 192.168.0.15:80;
server 192.168.0.14:88;
server 192.168.0.15:80;
fair;
server squid2:3128;
hash $request_uri;
hash_method crc32;
}
3. upstream配置參數
例子:
upstream bakend{
ip_hash;
server 127.0.0.1:9090 down;
server 127.0.0.1:8080 weight=2;
server 127.0.0.1:6060 max_fails=1 fail_timeout=10s;
server 127.0.0.1:7070 backup;
}
3) max_fails :允許請求失敗的次數默認為1.當超過最大次數時,返回proxy_next_upstream 模塊定義的錯誤
4) fail_timeout:max_fails次失敗后,暫停改服務的時間,超過時間后繼續向該服務發送流量,默認為10s。
5) backup:備用服務器,其它所有的非backup機器down或者忙的時候,啟用backup機器。
4.容錯機制
1) Nginx 默認判斷失敗節點狀態以connect refuse和time out狀態為准,不以HTTP錯誤狀態進行判斷失敗,因為HTTP只要能返回狀態說明該節點還可以正常連接,所以nginx判斷其還是存活狀態;
2) 除非添加了fastcgi_next_upstream或proxy_next_upstream指令設置對404、502、503、504、500和time out等錯誤進行轉到備機處理;
3) 在next_upstream過程中,會對fails進行累加,如果備用機處理還是錯誤則直接返回錯誤信息(但404不進行記錄到錯誤數,如果不配置錯誤狀態也不對其進行錯誤狀態記錄)
綜述,nginx記錄錯誤數量timeout和connect refuse是永遠被記錄錯誤狀態,而502、500、503、504只有在配置proxy_next_upstream或fastcgi_next_upstream后nginx才會記錄這4種HTTP錯誤到fails中,當fails大於等於max_fails時,則該節點失效;
注意:
fastcgi_next_upstream與proxy_next_upstream支持的錯誤並不一致:
fastcgi_next_upstream:error
| timeout
| invalid_header
| http_500
| http_503
| http_403
| http_404
| off
proxy_next_upstream:error
| timeout
| invalid_header
| http_500
| http_502
| http_503
| http_504
|http_403
| http_404
| off
...
當fastcgi的服務異常時,因為fastcgi_next_upstream不支持http_502錯誤,無法對fastcgi異常進行判斷,
所以fastcgi_pass與proxy_pass處理的規則也不相同:
|
fastcgi_pass
|
proxy_pass
|
---|---|---|
輪詢 | 默認會將請求發送到下一個服務節點上 | 默認不會將請求發送到下一個服務節點上,直接拒絕請求 在proxy_next_upstream中配置http_502錯誤,則會將請求發送到下一個服務節點上 |
weight | 默認會將請求發送到下一個服務節點上 | 默認不會將請求發送到下一個服務節點上,直接拒絕請求 在proxy_next_upstream中配置http_502錯誤,則會將請求發送到下一個服務節點上 |
hash | 默認不會將請求發送到下一個服務節點上,直接拒絕請求 |
默認不會將請求發送到下一個服務節點上,直接拒絕請求 在proxy_next_upstream中配置http_502錯誤,則會將請求發送到下一個服務節點上 |