keepalived是配置HA常用的软件,基于vrrp协议,可以使多台服务器共用一个或多个虚拟ip,其中优先级最高的主服务器持有虚拟ip,如果主服务器宕机,虚拟ip会在极短的时间内切换到优先级最高的从服务器上,从而避免单点故障。通常配合lvs、nginx、HAproxy等使用。我的环境是两台nginx+keepalived实现高可用。

一. 安装keepalived

两台服务器都要安装keepalived,keepalived依懒openssl,同时编译安装还要装gcc

yum install openssl openssl-devel gcc gcc-c++ 

编译keepalived,经典三步:

./configure --prefix=/opt/keepalived/ && make && make install

将配置文件复制到相应目录

mv /opt/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/keepalived
mv /opt/keepalived/sbin/keepalived /usr/sbin/
mv /opt/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
mv /opt/keepalived/etc/keepalived /etc/

二.配置

keepalived自带了很多samples,在/etc/keepalived/samples下.通常来说,主服务器和从服务器的配置除了优先级和state都是一样的

1.最简单的双机共享ip配置

! 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_instance VI_1 {
    state MASTER    //指定主服务器,如果是从服务器,这里要设置成BACKUP 
    interface eth1  //对应的网卡接口
    virtual_router_id 51 //虚拟路由id号,主备要一样,相同VRID为一个组,决定多播地址,一般不大于255
    priority 100    //优先级 越大优先级越高 从服务器的优先级要小于主服务器,如果有多个从服务器,要设置不同优先级
    advert_int 1    //健康检查间隔
    authentication {
        auth_type PASS
        auth_pass 1111
    }
virtual_ipaddress {
    192.168.56.103   //共享的虚拟ip,可以有多个
    192.168.56.104
}

在两台服务器上启动keepalived:

service keepalived start

keepalived的虚拟ip用ifconfig命令是看不到的,要用ip a命令来查看.

2.nginx+keepalived配置
keepalived支持vrrp_script脚本,通过自定义脚本ngix_pid.sh来检查nginx状态,如果nginx进程不存在就启动nginx

! Configuration File for keepalived
global_defs {
   notification_email {
     sa@52os.net
   }
   notification_email_from root
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL
}

vrrp_script chk_http_port {
            script "/opt/keepalived/nginx_pid.sh"
            interval 2
            weight 2
}

vrrp_instance VI_1 {
    state MASTER     //初始为master状态
    interface eth0
    virtual_router_id 51  //虚拟路由id号,不大于255
    mcast_src_ip 192.168.1.60
    priority 150  //配置的优先级要最高
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }

virtual_ipaddress {
    192.168.1.46
    }
track_script {
    chk_http_port
    }
}

nginx_pid.sh脚本内容:

#!/bin/bash
A=`ps -C nginx --no-header |wc -l`               
if [ $A -eq 0 ];then                                       
            /usr/local/nginx/sbin/nginx
            sleep 3
            if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
                   killall keepalived
            fi
fi

Keepalived是工作是OSI参考模型的3/4/5层,它的检测机制支持: ICMP包,端口检测,应用层检查(例如http get)等

参考文章:
http://www.keepalived.org
http://lanlian.blog.51cto.com/6790106/1303195
http://freeloda.blog.51cto.com/2033581/1280962