上一章我们讲解了nginx的集群,那么如果碰到下面的问题,我们改怎么办了?
分发器宕机怎么办
数据服务器宕机怎么办
别怕,我们有Keepalive
Keepalived的作⽤是检测服务器的状态,如果有⼀台web服务器宕机,或⼯作出现故障,Keepalived将检测到,并将有故障的服务器从系统中剔除,同时使⽤其他服务器代
替该服务器的⼯作,当服务器⼯作正常后Keepalived⾃动将服务器加⼊到服务器群中,这些⼯作全部⾃动完成,不需要⼈⼯⼲涉,需要⼈⼯做的只是修复故障的服务器。
⼀个监控+⾃愈的软件
1:根据提供地址进行下载
http://www.keepalived.org/download.html
wget http://www.keepalived.org/software/keepalived-2.0.8.tar.gz
2:解压到文件夹
[root@localhost src]# tar -zxvf keepalived-2.2.4.tar.gz
[root@localhost src]# ./configure --prefix=/usr/local/keepalived
3:编译和安装
[root@localhost src]#make
[root@localhost src]#make install
软件环境部署
1分发器 nginx+keepalived
2数据服务器 Nginx
3配置Nginx分发器
4配置数据服务器⻚⾯(web01 web02)
5配置keepalived.conf
6测试
配置Nginx集群
upstream web {
server 192.168.10.42 max_fails=2 fail_timeout=3;
server 192.168.10.43 max_fails=2 fail_timeout=3;
}
server {
listen 80;
server_name localhost;
ocation / {
proxy_pass http://web;
}
}
配置keepalived
#找到配置文件,进行备份后编辑
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id NGINX_DEVEL
}
#定义一个脚本,名字叫做check_nginx
vrrp_script check_nginx {
script "/etc/keepalived/nginx_pid.sh" #脚本路径
interval 2 #每2s运行一次脚本
fall 1 #失败次数1
}
vrrp_instance nginx { #一个实例就是一个集群,名称为nginx
state MASTER #定义状态为主播
interface ens33 #配置网卡名称,指向本机具体的网卡名称
mcast_src_ip 192.168.10.40 #宣告自己还活着,闲杂人等都给朕退下
virtual_router_id 51 #指定vrrp实例id,范围0-255
priority 100 #指定优先级,优先级高的将成为master组播
advert_int 1 #多久发一次组播
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
check_nginx
}
virtual_ipaddress { #虚拟ip
192.168.10.213/24
}
}
关联脚本 nginx_pid.sh(注意是上文中定义的脚本路径)
#chmod 755 /etc/keepalived/nginx_pid.sh
#vim /etc/keepalived/nginx_pid.sh
#!/bin/bash
nginx_kp_check () {
nginxpid=`ps -C nginx --no-header |wc -l`
if [ $nginxpid -eq 0 ];then
/usr/local/nginx/sbin/nginx
sleep 1
nginxpid=`ps -C nginx --no-header |wc -l`
if [ $nginxpid -eq 0 ];then
systemctl stop keepalived
fi
fi}
启动keepalived
systemctl start keepalived
配置备份Nginx分发器
backuo.ayitula.com
#cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id NGINX_DEVEL
}
vrrp_script check_nginx {
script "/etc/keepalived/nginx_pid.sh"
interval 2
fall 1
}
vrrp_instance nginx {
state BACKUP
interface ens33
mcast_src_ip 192.168.10.41
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
check_nginx
}
virtual_ipaddress {
192.168.10.213/24
}
}
大功告成,加油~~~~