Nginx的一个优点:Nginx可以自己进行健康检查,发现故障server会自动剔除,修复后自动添加;
这里我们需要5台虚拟机进行部署;
1台nginxserver负责反向代理的负载均衡;
4台作为Apache server;其中2台模拟html;2台模拟php;
Nginx调度算法介绍
Nginx目前支持自带3种负载均衡策略,还有2种常用的第三方策略。
1)RR(默认)
每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。
如下代码:
这里我配置了2台服务器,当然实际上是一台,只是端口不一样而已,而8081的服务器是不存在的,也就是说访问不到,但是我们访问http://localhost 的时候,也不会有问题,会默认跳转到http://localhost:8080 具体是因为Nginx会自动判断服务器的状态,如果服务器处于不能访问(服务器挂了),就不会跳转到这台服务器,所以也避免了一台服务器挂了影响使用的情况,由于Nginx默认是RR策略,所以我们不需要其他更多的设置。
2)权重
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
例如:
那么10次一般只会有1次会访问到8081,而有9次会访问到8080
3)ip_hash
上面的2种方式都有一个问题,那就是下一个请求来的时候请求可能分发到另外一个服务器,当我们的程序不是无状态的时候(比如采用了session保存数据),这时候就有一个很大的很问题了,比如把登录信息保存到了session中,那么跳转到另外一台服务器的时候就需要重新登录了,所以很多时候我们需要一个客户只访问一个服务器,那么就需要用ip_hash了,ip_hash的每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
例如:
配置Nginx.conf
[root@sxb-1 conf]# vim nginx.conf upstream htmlserver { server 192.168.88.102:80; server 192.168.88.103:80; } upstream phpserver { server 192.168.88.104:80; server 192.168.88.105:80; } server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location ~* \.html$ { proxy_pass http://htmlserver; } location ~* \.php$ { proxy_pass http://phpserver; }
基础搭建我们就可以使用了
测试:
[root@sxb-1 ~]# curl 192.168.88.101/index.html 103 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 102 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 103 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 102 html
[root@sxb-1 ~]# curl 192.168.88.101/index.php 104 php [root@sxb-1 ~]# curl 192.168.88.101/index.php 105 php [root@sxb-1 ~]# curl 192.168.88.101/index.php 104 php [root@sxb-1 ~]# curl 192.168.88.101/index.php 105 php
测试 自动剔除、自动添加:
对102 进行防火墙策略 如果添加的策略是DROP,测试是会发生卡顿;(DROP为丢弃,Nginx会持续发送,直到超时;)
[root@sxb-1 ~]# iptables -t filter -A INPUT -p tcp --dport 80 -j REJECT [root@sxb-1 ~]# curl 192.168.88.101/index.html 103 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 103 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 103 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 103 html
清除策略:
[root@sxb-1 ~]# iptables -F [root@sxb-1 ~]# curl 192.168.88.101/index.html 103 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 103 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 102 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 103 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 102 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 103 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 102 html [root@sxb-1 ~]# curl 192.168.88.101/index.html 103 html