
upstream模塊介紹
Nginx的負載均衡功能來自於其模塊ngx_http_upstream_module模塊,該模塊支持的代理方式有:
1. uwsgi_pass
2. fastcgi_pass
3. proxy_pass
4. memcached_pass
ngx_http_upstream_module模塊允許Nginx定義一組或多組節點服務器,使用時可以通過proxy_pass代理方式,把用戶請求發送到事先定於好的upstream組中。具體寫法就是
upstream www_pools {
server x.x.x.x;
server x.x.x.x;
}
proxy_pass http://www_pools;
完整的upstream配置案例
upstream www_pools {
server 192.168.178.121;
server 192.168.178.122:80 weight=1 max_fails=1 fail_timeout=10s;
server 192.168.178.123:80 weight=10 max_fails=2 fail_timeout=20s backup;
server 192.168.178.124:80 wetight=10 max_fails=2 fail_timeout=20s backup;
}
使用域名及socket的upstream配置
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com:8080;
server unix:/tmp/backend3;
server backend3.example.com:8080 backup;
}
upstream參數
# 參數解釋
server是固定關鍵字,后面跟着服務器ip或是域名,默認是80端口,也可以指定端口
weight表示節點的權重,數字越大,分配的請求越多,注意nginx結尾的分號
max_fails Nginx嘗試連接后端節點失敗的次數,根據企業情況調整,默認是1
backup 其它所有的非backup機器down或者忙的時候,請求backup機器,實現熱備效果。
fail_timeout 在max_fails定義的次數失敗后,距離下次檢查的間隔時間,默認10s
down 表示當前主機暫停,不參與負載均衡
upstream模塊的內容應放於nginx.conf配置中的 http{}標簽內
其默認調度算法是wrr(權重輪詢,weighted round-robin)
upstream模塊調度算法
【rr輪詢調度算法】
【wrr權重輪詢】
upstream backend {
server 192.168.178.122 weight=1;
server 192.168.178.121 weight=2;
}
【ip_hash】
upstream chaoge_backend {
ip_hash;
server 192.168.178.121;
server 192.168.178.122;
}
【fail】
該算法根據后端服務器節點的響應時間來分配,響應時間短的優先分配。nginx本身不支持fail形式,如果要支持該算法,必須下載nginx的upstream模塊。
upstream chaoge_backend {
fair;
server 192.168.178.121;
server 192.168.178.122;
}
【least_conn】
該算法根據后端節點的連接數決定分配請求,哪個機器連接數少,就發給誰。
【url_hash】
需要單獨安裝hash模塊
upstream chaoge_backend {
server squid1:3128;
server squid:3128;
hash $request_uri;
hash_method crc32;
}
proxy_pass指令
案例1
在nginx.conf配置文件中定義
location /name/ {
proxy_pass http://127.0.0.1/remote/;
}
例如當請求URL是: http://192.168.178.121/name ,會進入該locaiton的作用域,通過參數proxy_pass請求轉發給了http://127.0.0.1/remote/
案例2
location ~ .*\.php$ {
proxy_pass http://www.example.cn$request_uri;
proxy_set_header Host $proxy_host;
proxy_set_header X-Forwarded-For $remote_addr;
}
所有請求以.php結尾的URL,進行轉發
proxy_pass參數
| 參數 | 作用解釋 |
| proxy_set_header | 設置反向代理向后端發送的http請求頭信息,如添加host主機頭部字段,讓后端服務器能夠獲取到真是客戶端的IP信息等。 |
| client_body_buffer_size | 指定客戶端請求主體緩沖區大小 |
| proxy_connect_timeout | 反向代理和后端節點連接的超時時間,也是建立握手后等待響應的時間 |
| proxy_send_timeout | 表示代理后端服務器的數據回傳時間,在規定時間內后端若數據未傳完,nginx會斷開連接 |
| proxy_read_timeout | 設置nginx從代理服務器獲取數據的超時時間 |
| proxy_buffer | 設置緩沖區的數量大小 |
