8-nginx负载均衡

nginx.jpg

查看与启用stream模块

1
nginx -V 2>&1 | grep -- '--with-stream'

-with-stream=dynamic,状态为已经安装但是没有默认加载,需要手动进行加载,

服务器组

upstream设置后端服务器组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
upstream test_team{    #设置服务器组名为test_team
#ip_hash; #,会话保持,请求按照IP的hash结果分配,每个访客固定访问一个后端服务器,不能与server中的weigth一同使用,并且必须是最前端的服务器,这样才能获取到客户端的IP

#hash $remote_addr consistent;
#根据指定的键进行哈希,更加灵活,可以使用任意变量作为哈希键,适用于需要更复杂哈希策略的场景。
#可以通过 consistent 关键字启用一致性哈希,减少服务器增减时的哈希重新分布。

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;
}
}

例三:对特定资源实现负载均衡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
}