server 192.168.27.11; server 192.168.27.12 weight=5; # weight=5权重为5,默认为1,越大越优先用于处理请求 server 192.168.27.13 fail_timeout=10s max_fails=3; #10秒内连续三次失败,则在随后的10秒内认为服务器是无效的 server 192.168.27.14 backup; #备用服务器,只有在正常服务器处于down或者busy时才会被使用 server 192.168.27.15 down; #标记为永久down状态,通常与ip_hash配合使用 #last_conn #把请求分派给连接数最少的服务器 }
负载均衡
例一:一般轮询规则
1 2 3 4 5 6 7 8 9 10 11 12 13 14
upstream backend{ server 192.168.27.11:80; server 192.168.27.12:80; server 192.168.27.13:80; } server { listen 80; server_name www.test.demo; index index.html; location /{ proxy_pass http://backend; proxy_set_header HOST $host; } }
例二:加权轮询规则
1 2 3 4 5 6 7 8 9 10 11 12 13 14
upstream backend{ server 192.168.27.11:80 weight=3; server 192.168.27.12:80 weight=2; server 192.168.27.13:80 weight=1; } server { listen 80; server_name www.test.demo; index index.html; location /{ proxy_pass http://backend; proxy_set_header HOST $host; } }
upstream file{ server 192.168.27.11:80; server 192.168.27.12:80; server 192.168.27.13:80; } upstream video{ server 192.168.27.11:80; server 192.168.27.12:80; server 192.168.27.13:80; } server { listen 80; server_name www.test.demo; index index.html; location /file/{ proxy_pass http://file; } location /video/{ proxy_pass http://video; } }
例四:带有URL重写的负载均衡
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
upstream backend{ server 192.168.27.11:80 weight=3; server 192.168.27.12:80 weight=2; server 192.168.27.13:80 weight=1; } server { listen 80; server_name www.test.demo; index index.html; location /backend/{ rewrite ^(.*) XXX last; } location /{ proxy_pass http://backend; proxy_set_header HOST $host; } }
例五:哈希
1 2 3 4 5 6
upstream backend_servers { hash $remote_addr consistent; server 192.168.1.101; server 192.168.1.102; server 192.168.1.103; }