nginx+keepalived 主备实现高可用

nginx+keepalived 主,当一台主机挂掉,由备用主机顶上

主机:

192.168.59.102:master

192.168.59.103:backup

 

1、安装nginx(两台主机都安装)

https://www.cnblogs.com/leihongnu/p/16265539.html

将nginx首页编辑为:102和103方便区分

 

2、安装keepalived(两台主机都安装)

安装下载地址:https://github.com/acassen/keepalived/tags

挑一个版本下载,解压

#tar -zxvf keepalived-1.4.5.tar.gz

编译

#cd keepalived-1.4.5

#安装路径为/usr/local/keepalived

#./configure --prefix=/usr/local/keepalived --with-init=SYSV

# make && make install

拷贝配置文件到系统目录方便启动

# mkdir /etc/keepalived

# cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/

#chmod +x /etc/init.d/keepalived 

# cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/

# cp /usr/local/keepalived/sbin/keepalived /usr/sbin/

# ln -s /usr/local/keepalived/sbin/keepalived /sbin/

添加启动服务  

#chkconfig --add keepalived

#systemctl daemon-reload

编辑脚本 /etc/keepalived/nginx_check.sh(两台服务器都要编辑)

#!/bin/bash
A=`netstat -tnlp | grep 80 | grep nginx | wc -l`

if [ $A -eq 0 ];then

#nginx关闭,/usr/local/nginx/sbin/nginx重启
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
sleep 2
if [ `netstat -tnlp | grep 80 | grep nginx | wc -l` -eq 0 ];then
# 重启不行nginx则关闭keepalived服务
systemctl stop keepalived
fi
fi

给脚本添加执行权限

#chmod +x /etc/keepalived/nginx_check.sh

 

编辑配置文件 192.168.59.102 master

vi /etc/keepalived/keepalived.conf 

! Configuration File for keepalived

global_defs {

#路由ID,当前安装keepalived的节点主机标识符,需保证全局唯一

 router_id LVS_DEVEL_01

}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh"   #检查本地nginx是否存活脚本
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER    #定义为从,可选项MASTER|BACKUP
interface enp0s3  #使用的网卡 可以用ip addr查看
virtual_router_id 51  #定义组ID,matser和backup必须一致
priority 100  #优先级 master必须比backup大(0-250)
advert_int 1  #多久在组里广播一下自己的心跳信息,默认单位为秒s
nopreempt
authentication {
auth_type PASS

auth_pass 1111  #主从两个服务器的字符串要设定为相同的
}
virtual_ipaddress {
192.168.59.211/24   #虚拟ip
}
track_script {
chk_nginx
}
}

 

 

编辑配置文件 192.168.59.103 backup

vi /etc/keepalived/keepalived.conf 

! Configuration File for keepalived

global_defs {
router_id LVS_DEVEL_02
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh"   #检查本地nginx是否存活脚本
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP #定义为从,可选项MASTER|BACKUP
interface enp0s3  #使用的网卡 可以用ip addr查看
virtual_router_id 51  #定义组ID,matser和backup必须一致
priority 90 #优先级 master必须比backup大(0-250)
advert_int 1  #多久在组里广播一下自己的心跳信息,默认单位为秒s
nopreempt
authentication {
auth_type PASS

auth_pass 1111  #主从两个服务器的字符串要设定为相同的
}
virtual_ipaddress {
192.168.59.211/24   #虚拟ip
}
track_script {
chk_nginx
}
}

3、启动nginx和keepalived服务

 

 

 

 4、验证

关闭192.168.59.102的keepalived服务

 

posted @   leihongnu  阅读(80)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示