步骤一:部署实施后端Web服务器
1)部署后端Web1服务器
后端Web服务器可以简单使用yum方式安装httpd实现Web服务,为了可以看出后端服务器的不同,可以将两台后端服务器的首页文档内容设置为不同的内容。
[root@web1 ~]# yum -y install httpd
[root@web1 ~]# echo "192.168.2.100" > /var/www/html/index.html
[root@web1 ~]# systemctl restart httpd
[root@web2 ~]# yum -y install httpd
[root@web2 ~]# echo "192.168.2.200" > /var/www/html/index.html
[root@web2 ~]# systemctl restart httpd
使用备份配置文件,覆盖旧的配置文件
[root@proxy conf]# cp nginx.conf.default nginx.conf
cp:是否覆盖"nginx.conf"? y
修改配置文件:
35 upstream webserver {
36 server 192.168.2.100:80;
37 server 192.168.2.200:80;
定义集群:upstream 集群名 server 主机名 )(集群中的主机可以有多台主机)
- #使用upstream定义后端服务器集群,集群名称任意(如webserver)
- #使用server定义集群中的具体服务器和端口
49 location / {
50 root html; //这句话的意思,访问的网页目录在我本机的html目录下,所以在这句话前面,或者注释
51 index index.html index.htm;
49 location / {
50 proxy_pass http://webserver;
51 root html;
52 index index.html index.htm;
53 }
重起nginx服务:
[root@proxy conf]# nginx -s reload
3)客户端使用浏览器访问代理服务器测试轮询效果
[root@clent ~]# curl http://192.168.4.5
//使用该命令多次访问查看效果
192.168.2.200
[root@clent ~]# curl http://192.168.4.5
192.168.2.100
步骤二:配置upstream服务器集群池属性
1)设置失败次数,超时时间,权重
weight可以设置后台服务器的权重,max_fails可以设置后台服务器的失败次数,fail_timeout可以设置后台服务器的失败超时时间。
35 upstream webserver {
36 server 192.168.2.100:80 weight=1 max_fails=1 fail_timeout=30;
37 server 192.168.2.200:80 weight=2 max_fails=2 fail_timeout=30;
38 server 192.168.2.101 down;
39 }
#weight设置服务器权重值,默认值为
1
#max_fails设置最大失败次数
#fail_timeout设置失败超时时间,单位为秒
#down标记服务器已关机,不参与集群调度
50 location / {
51 proxy_pass http://webserver;
52 root html;
53 index index.html index.htm;
重起nginx服务
[root@proxy conf]# nginx -s reload
关闭一台后端服务器:
[root@web1 ~]# systemctl stop httpd
客户端访问:
[root@clent ~]# curl http://192.168.4.5
192.168.2.200
[root@clent ~]# curl http://192.168.4.5
192.168.2.200
[root@clent ~]# curl http://192.168.4.5
192.168.2.200
[root@clent ~]# curl http://192.168.4.5
192.168.2.200
再次启动后端服务器:
//要等30秒才会有这样的结果
192.168.2.100
[root@clent ~]# curl http://192.168.4.5
192.168.2.200
[root@clent ~]# curl http://192.168.4.5
192.168.2.200
[root@clent ~]# curl http://192.168.4.5
192.168.2.100
步骤三:配置upstream服务器集群的调度算法
1)设置相同客户端访问相同Web服务器
upstream webserver {
ip_hash;
server 192.168.2.100:80 weight=1 max_fails=2 fail_timeout=10;
server 192.168.2.200:80 weight=2 max_fails=2 fail_timeout=10;
server 192.168.2.101 down;
}
location / {
proxy_pass http://webserver;
root html;
index index.html index.htm;
}
重起nginx服务:
[root@proxy conf]# nginx -s reload
客户端访问:
//一直显示的一台后端服务起
[root@clent ~]# curl http://192.168.4.5
192.168.2.100
[root@clent ~]# curl http://192.168.4.5
192.168.2.100
[root@clent ~]# curl http://192.168.4.5
192.168.2.100
[root@clent ~]# curl http://192.168.4.5
192.168.2.100
模拟一台后端数据库坏掉:
[root@web1 ~]# systemctl stop httpd
再次访问客户端: //立刻转换到另外一台后端服务器,取代原来的后端服务器进行工作
[root@clent ~]# curl http://192.168.4.5
192.168.2.200
[root@clent ~]# curl http://192.168.4.5
192.168.2.200
[root@clent ~]# curl http://192.168.4.5
192.168.2.200