参看文献 https://blog.csdn.net/u012410733/article/details/57078407
nginx的安装,这里就不再讲了
这里使用了两台服务器
192.168.37.135 主
192.168.37.136 从
分别在两台服务器上安装keepalived
1.#安装 popt
2.yum install openssl-devel
3.
4.cd /usr/local/software
5.wget http://www.keepalived.org/software/keepalived-1.2.8.tar.gz
6.tar -zxvf keepalived-1.2.8.tar.gz -C /usr/local/
7.cd ../keepalived-1.2.8
8../configure --prefix=/usr/local/keepalived --sysconf=/etc
9.make && make install
10.
11.cp /usr/local/keepalived/sbin/keepalived /bin/
12.chkconfig --add keepalived
13.#设置开机启动
14.chkconfig keepalived on
15.#启动keepalive服务
16./etc/init.d/keepalived start
之后可以使用
service keepalived start|stop|restart
然后在主机上运行 vim /etc/keepalived/keepalived.conf 修改配置
! Configuration File for keepalived
global_defs {
router_id 192.168.37.135
}
vrrp_script check_nginx {
script "/root/nginx_check.sh"
interval 2
weight -20
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass bhz
}
virtual_ipaddress {
192.168.37.110
}
track_script {
check_nginx
}
}
从机上运行 vim /etc/keepalived/keepalived.conf 修改配置
! Configuration File for keepalived
global_defs {
router_id 192.168.37.136
}
vrrp_script check_nginx {
script "/root/nginx_check.sh"
interval 2
weight -20
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass bhz
}
virtual_ipaddress {
192.168.37.110
}
track_script {
check_nginx
}
}
简单描述:主机的state是MASTER,从机的是BACKUP;interface是网卡,可以输入ip a 查看网卡信息 ;priority是权重,主机是100,从机是90,当检查心跳的时候,发现当前的nginx或keepalived停止了,权重值就减少20,这样的话就会比另一台服务器的权重小,这个规则可以自定义;
在root目录先新建心跳脚本 nginx_check.sh
#!/bin/sh
A=`ps -C nginx --no-header |wc -l`
echo 'hello'
if [ $A -eq 0 ]
then
killall keepalived
fi
注释:ps -C nginx --no-header |wc -l 这句是获取正在运行的nginx服务的个数
若是使用上面这个脚本的话必须先启动nginx,再启动keepalived,因为如果没有先启动nginx的话,执行这个脚本发现没有启动nginx直接就把keepalived进程杀死了
配置已经完成了,启动两台服务器的nginx /usr/local/nginx/sbin/nginx 这个是我的nginx的启动目录
启动两台服务器的keepalived service keepalived start
输入虚拟ip
这个时候访问到的是主机的nginx;而且在主机输入 ip a时,可以看到有虚拟的ip地址,而查看从机时是没有虚拟ip的
这里我测试的时候发现一个奇怪的问题,直接停止nginx服务的话,再次访问虚拟ip 的话就访问不了了,只有先停止keepalived服务再停止nginx服务有效果
将主机的keepalived服务停止 service keepalived stop
将主机的nginx 服务停止 /usr/local/nginx/sbin/nginx -s stop
再次输入ip a查看ip
再次访问虚拟地址
发现访问到的是从机的nginx
现在又重新启动主机的nginx和keepalived服务
/usr/local/nginx/sbin/nginx
service keepalived start
再次访问虚拟ip
正式环境的心跳脚本:
#!/bin/sh
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ]
then
/usr/local/nginx/sbin/nginx //重启nginx,若nginx启动失败则停止keepalived
sleep 2
if [ `ps -C nginx --no-header |wc -l` -eq 0 ]
then
killall keepalived
fi
fi
#!/bin/sh A=`ps -C nginx --no-header |wc -l` if [ $A -eq 0 ] then /usr/local/nginx/sbin/nginx sleep 2 if [ `ps -C nginx --no-header |wc -l` -eq 0 ] then killall keepalived fi fi
若使用的是上面的心跳脚本,则可以只启动keepalived而不需要先启动nginx