1、keepalive的概数
Keepalived最初为LVS设计,专门监控各种服务器节点状态,Keepalived后来加入了VRRP功能,防止单点故障
2、keepalived工作原理
Keepalived检测每个服务器节点状态
当服务器节点出现异常或工作出现故障,Keepalived会将故障节点从集群系统中删除
故障节点恢复后,Keepalived在将其加入到集群中
所有工作自动完成,无需人工干预
3、环境准备(2台proxy服务器、2台web服务器)
关闭防火墙、关闭SELinux、配置YUM源
systemctl stop firewalld
systemctl enable firewalld
setenforce 0
Keepalived软件包镜像自带,配置好yum源可直接安装
proxy1服务器操作(2台proxy服务器配置除了服务器优先级和名字即MASTER不一样,其它都一样,模式为主从模式)
yum -y install keepalived
修改keepalived配置文件(要修改的只有网卡名、服务器优先级、VIP地址)
vim /etc/keepalived/keepalived.conf
# vrrp_strict //注释改行,否则keepalived会开启iptables防火墙
vrrp_instance VI_1 {
state MASTER //MASTER为主服务器
interface ens33 //当前使用的网卡名
virtual_router_id 51 //虚拟路由id号
priority 150 //当前服务器优先级,数字越大越优先
advert_int 1 //检测心跳时间为1秒
authentication { //身份验证方式
auth_type PASS //密码验证
auth_pass 1111 //密码为1111
}
virtual_ipaddress {
192.168.0.70/24 //VIP地址(虚拟ip)
}
}
启动keepalived服务
systemctl start keepalived
验证VIP地址
ip a s
安装nginx依赖包
yum -y install gcc pcre-devel openssl-devel
解压源码包
tar -xf nginx-1.12.2.tar.gz
cd nginx-1.12.2
检测环境
./configure
编译并安装
make && make install
修改Nginx配置文件配置调度器
upstream webserver { #定义集群, 和集群名字
server 192.168.0.63:80;#集群内主机
server 192.168.0.64:80;
}
location / {
proxy_pass http://webserver;调用集群名字
root html;
index index.html index.htm;
/usr/local/nginx/sbin/nginx //启动服务
web服务器操作(2台nginx 服务器配置基本一样)
安装nginx依赖包
yum -y install gcc pcre-devel openssl-devel
解压源码包
tar -xf nginx-1.12.2.tar.gz
cd nginx-1.12.2
检测环境
./configure
编译并安装
make && make install
启动服务
/usr/local/nginx/sbin/nginx
修改Nginx默认首页
echo web3 > /usr/local/nginx/html/index.html
/usr/local/nginx/sbin/nginx //启动Nginx
echo web4 > /usr/local/nginx/html/index.html
/usr/local/nginx/sbin/nginx //启动Nginx
编写监控脚本(MASTER、BACKUP均编写此脚本)
vim /etc/keepalived/ch_nginx.sh
#!/bin/bash
counter=$(ps -C nginx | grep -v PID | wc -l) //取命令结果赋值给变量
if [ $counter=0 ];then //判断变量里的值如果等于0
/usr/local/nginx/sbin/nginx //启动nginx服务
sleep 5 //由于启动服务需要时间,休眠5秒
counter=$(ps -C nginx | grep -v PID | wc -l)
if [ $counter=0 ];then //在判断变量里的值如果还等于0
systemctl stop keepalived //停掉keepalived服务
fi
fi
chmod +x /etc/keepalived/ch_nginx.sh //授权可执行
修改配置文件,指定监控脚本(MASTER、BACKUP均配置)
vim /etc/keepalived/keepalived.conf
vrrp_script chk_nginx { #脚本模块
script "/etc/keepalived/ch_nginx.sh" #脚本路径
interval 2 #检测脚本时间
}
track_script { #添加监控条件
chk_nginx #脚本模块后边定义的名字
virtual_ipaddress {
192.168.0.70/24
停止Nginx服务(停掉主服务器的)
/usr/local/nginx/sbin/nginx -s stop
查看服务进程
ss -anptul | grep nginx
提示:脚本检测到Nginx进程为0时,将执行脚本启动Nginx服务
刷新一下(这就是负载均衡,加入脚本防止单点故障,就是高可用)