1、准备:两台服务器
主:192.168.222.131
从:192.168.222.133
虚拟IP:192.168.222.132
2、分别安装nginx
3、安装keepalived
1)官网下载对应版本安装包
Keepalived for Linuxhttps://www.keepalived.org/download.html2)创建/data/keepalived目录,将压缩包上传到此目录并解压
# 创建目录
mkdir -p /data/keepalived
# 进入目录
cd /data/keepalived
#解压
tar -xzvf keepalived-2.2.8.tar.gz
3)安装keepalived
# 进入解压后的目录
cd /data/keepalived/keepalived-2.2.8
# 安装
./configure --prefix=/data/keepalived
make && make install
4、配置文件调整
1)nginx配置文件 /data/nginx/conf/nginx.conf,根据业务实际需要配置
2)keepalived配置文件 /data/keepalived/,主、从服务器都需要配置
! Configuration File for keepalived
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.200.1
smtp_connect_timeout 30
router_id LVS_DEVEL
vrrp_skip_check_adv_addr
vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
}
vrrp_script check_nginx {
script "/data/keepalived/nginx_check.sh" # 检测脚本目录
interval 2 # 检测脚本执行的间隔,单位是秒
# user root # 指定用户执行脚本
weight 2 # 权重
}
vrrp_instance VI_1 {
state MASTER # 主机值为MASTER,从机值为BACKUP
interface ens33 # 网卡名称,可以使用ifconfig命令查看
virtual_router_id 51 # 路由id,主从机需要保持一致
priority 100 # 权重,主机需要比从机大
advert_int 1 # 默认每隔1秒发送一次心跳检测
authentication {
auth_type PASS
auth_pass 1111 # 认证密码,主从机需要保持一致
}
track_script {
check_nginx # 执行一个检测脚本
}
virtual_ipaddress {
192.168.222.132 # 虚拟IP,主从机保持一致,本次为192.168.222.132,支持多个
}
}
3)nginx检测脚本,在/data/keepalived目录下,创建nginx_check.sh文件,并添加执行权限
#!/bin/bash
nginx_process=`ps -C nginx --no-header | wc -l`
if [ $nginx_process -eq 0 ];then
/data/nginx/sbin/nginx
sleep 2
if [ `ps - C nginx --no-header | wc -l` -eq 0 ];then
sudo killall keepalived
fi
fi
5、启动nginx和keepalived
# 启动nginx
/data/nginx/sbin/nginx
# 停止nginx
/data/nginx/sbin/nginx -s stop
# 重载nginx
/data/nginx/sbin/nginx -s reload
# 启动keepalived
systemctl start keepalived
# 加入开机自启
systemctl enable keepalived