Nginx+Keepalived配置主从双机热备

keepalive 是 VRRP 协议的完美实现, 通过vip(虚拟ip)来实现主从双击热备, 自动切换的高可用方案, nginx的主从是通过keepalived实现的。

keepalived 是为ipvs开发的, 会自动执行健康检查, 如果需要给其他服务提供高可用, 需要舍弃健康检查, 并自己手写检查脚本添加到vrrp中

1, 安装keepalived, 多台nginx的服务器上分别安装

yum install keepalived

也可以通过本地安装包进行安装

wget http://
tar -zxvf keepalived-1.2.15.tar.gz
cd keepalived
-1.2.15
.
/configure --sysconf=/etc/  --with-kernel-dir=/usr/src/kernels/2.6.32-573.8.1.el6.x86_64
make
&& make install
ln
-s /usr/local/sbin/keepalived  /sbin/

最后创建软连接是为了, service keepalived start 进行启动

2, 修改keepavlied配置

修改keepalived.conf

主机: 

global_defs {
  notification_email {
    test@
163.com
  }
  notification_email_from keepalived@localhost
  smtp_server
127.0.0.1
  smtp_connect_timeout
30
  router_id LVS_MASTER
}
vrrp_script chk_http_port {
script
"/home/keepalived/check_nginx_pid.sh"
interval
2                          #(检测脚本执行的间隔)
weight
2
}
vrrp_instance VI_1 {
  #state MASTER
    state BACKUP
    nopreempt                     
    #设置非抢占模式时,修改“state MASTER”为“state BACKUP”,添加“nopreempt“
   
interface bond0
    virtual_router_id
51
    priority
100
    advert_int
1
    authentication {
        auth_type PASS
        auth_pass
1111
}
track_script {
chk_http_port            #(调用检测脚本)
}
    virtual_ipaddress {
       
192.168.208.126
    }
}

从机配置: 

global_defs {
  notification_email {
    test@
163.com
  }
  notification_email_from keepalived@localhost
  smtp_server
127.0.0.1
  smtp_connect_timeout
30
  router_id LVS_BACKUP
}
vrrp_script chk_http_port {
script
"/home/keepalived/check_nginx_pid.sh"
interval
2                          #(检测脚本执行的间隔)
weight
2
}
vrrp_instance VI_1 {
    state BACKUP
   
interface bond0
    virtual_router_id
51
    priority
66
    advert_int
1
    authentication {
        auth_type PASS
        auth_pass
1111
}
track_script {
chk_http_port            #(调用检测脚本)
}
    virtual_ipaddress {
       
192.168.208.126
    }
}

主机和从机的配置值在权重上有所差别, 别的都一样, 另外看了一些博客好多配置的权重都一样, 没有测试

3, vim /etc/keepalived/keepalived.conf

#!/bin/bash
if [ "$(ps -ef | grep"nginx: master process"| grep -v grep )" == "" ]
then
/usr/local/nginx/sbin/nginx
sleep
5
if [ "$(ps -ef | grep"nginx: master process"| grep -v grep )" == "" ]
then
killall keepalived
fi
fi
 

4, 绑定虚拟ip, 就可以了

keepalive 相关参数说明: 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/234611c6c911b8a690c170bda9278b9a.html