Nginx配置upstream實現負載均衡
如果Nginx沒有僅僅只能代理一臺服務器的話,那它也不可能像今天這么火,Nginx可以配置代理多臺服務器,當一臺服務器宕機之后,仍能保持系統可用。具體配置過程如下:
1. 在http節點下,添加upstream節點。
upstream linuxidc { server 10.0.6.108:7080; server 10.0.0.85:8980; }
2. 將server節點下的location節點中的proxy_pass配置為:http:// + upstream名稱,即“
http://linuxidc”.
location / { root html; index index.html index.htm; proxy_pass http://linuxidc; }
3. 現在負載均衡初步完成了。upstream按照輪詢(默認)方式進行負載,每個請求按時間順序逐一分配到不同的后端服務器,如果后端服務器down掉,能 自動剔除。雖然這種方式簡便、成本低廉。但缺點是:可靠性低和負載分配不均衡。適用于圖片服務器集群和純靜態頁面服務器集群。
除此之外,upstream還有其它的分配策略,分別如下:
weight(權重)
指定輪詢幾率,weight和訪問比率成正比,用于后端服務器性能不均的情況。如下所示,10.0.0.88的訪問比率要比10.0.0.77的訪問比率高一倍。
upstream linuxidc{ server 10.0.0.77 weight=5; server 10.0.0.88 weight=10; }
ip_hash(訪問ip)
每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個后端服務器,可以解決session的問題。
upstream favresin{ ip_hash; server 10.0.0.10:8080; server 10.0.0.11:8080; }
fair(第三方)
按后端服務器的響應時間來分配請求,響應時間短的優先分配。與weight分配策略類似。
upstream favresin{ server 10.0.0.10:8080; server 10.0.0.11:8080; fair; }
url_hash(第三方)
按訪問url的hash結果來分配請求,使每個url定向到同一個后端服務器,后端服務器為緩存時比較有效。
注意:在upstream中加入hash語句,server語句中不能寫入weight等其他的參數,hash_method是使用的hash算法。
upstream resinserver{ server 10.0.0.10:7777; server 10.0.0.11:8888; hash $request_uri; hash_method crc32; }
upstream還可以為每個設備設置狀態值,這些狀態值的含義分別如下:
down 表示單前的server暫時不參與負載.
weight 默認為1.weight越大,負載的權重就越大。
max_fails :允許請求失敗的次數默認為1.當超過最大次數時,返回proxy_next_upstream 模塊定義的錯誤.
fail_timeout : max_fails次失敗后,暫停的時間。
backup: 其它所有的非backup機器down或者忙的時候,請求backup機器。所以這臺機器壓力會最輕。
upstream bakend{ #定義負載均衡設備的Ip及設備狀態 ip_hash; server 10.0.0.11:9090 down; server 10.0.0.11:8080 weight=2; server 10.0.0.11:6060; server 10.0.0.11:7070 backup; }
Nginx的配置與部署研究,Upstream負載均衡模塊 http://www.linuxidc.com/Linux/2013-04/82526p2.htm
CentOS 6.2實戰部署Nginx+MySQL+PHP http://www.linuxidc.com/Linux/2013-09/90020.htm
使用Nginx搭建WEB服務器 http://www.linuxidc.com/Linux/2013-09/89768.htm
搭建基于Linux6.3+Nginx1.2+PHP5+MySQL5.5的Web服務器全過程 http://www.linuxidc.com/Linux/2013-09/89692.htm
CentOS 6.3下Nginx性能調優 http://www.linuxidc.com/Linux/2013-09/89656.htm
CentOS 6.3下配置Nginx加載ngx_pagespeed模塊 http://www.linuxidc.com/Linux/2013-09/89657.htm
CentOS 6.4安裝配置Nginx+Pcre+php-fpm http://www.linuxidc.com/Linux/2013-08/88984.htm
Nginx安裝配置使用詳細筆記 http://www.linuxidc.com/Linux/2014-07/104499.htm
Nginx日志過濾 使用ngx_log_if不記錄特定日志 http://www.linuxidc.com/Linux/2014-07/104686.htm
Nginx 的詳細介紹:請點這里
Nginx 的下載地址:請點這里