实现请求负载均衡

配置多个目标服务器,当一台服务器出现故障时,nginx 能将请求自动转向另一台服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
http {
sendfile_max_chunk 100k; #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
keepalive_timeout 65; #连接超时时间,默认为75s,可以在http,server,location块。

upstream mysvr {
server 127.0.0.1:7878 weight=2;
server 192.168.10.121:3333 backup weight=1; #根据权重进行轮询负载均衡
}
error_page 404 https://www.baidu.com; #错误页
server {
keepalive_requests 120; #单连接请求上限次数。
listen 9090; #监听端口
server_name 127.0.0.1; #监听地址
location ~*^.+$ { #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
#root path; #根目录
#index vv.txt; #设置默认页
proxy_pass http://mysvr; #请求转向mysvr 定义的服务器列表
deny 127.0.0.1; #拒绝的ip
allow 172.18.5.54; #允许的ip
# expires 设置客户端缓存
#expires 1h;
index index.php index.html;
# 资源重定向,如访问http://shop.devops.com/index.html后会被重写为访问 http://shop.devops.com/index.php,permanent表示永久重定向
rewrite /index.html /index.php permanent;

# 资源重定向,$request_filename为nginx的内置变量,表示资源文件路径
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=/$1 last;
break;
}
}
}
}

当服务器 ocalhost:8080 挂掉时,nginx能将请求自动转向服务器 192.168.101.9:8080。上面还加了一个 weight 属性,此属性表示各服务器被访问到的权重,weight 越高被访问到的几率越高。