1.maste主机:192.168.20.112

  slaver备机:192.168.20.137

VIP(虚拟IP,用于外网访问):192.168.20.100


2.安装nginx

3.安装keepalive

    tar -zxvf keepalived-1.2.15.tar.gz 

    cd keepalived-1.2.15    

    ./configure

    make 

    make install

4.软连接

    ln -s /usr/local/etc/keepalived/ /etc/

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

    ln -s /usr/local/etc/rc.d/init.d/keepalived  /etc/init.d/

    ln -s /usr/local/etc/sysconfig/keepalived  /etc/sysconfig/

    

5.修改主机keepalived配置文件

       vim /etc/keepalived/keepalived.conf

        

global_defs {

   notification_email {

     [email protected]



   }

   notification_email_from root@localhost

   smtp_server 127.0.0.1

   smtp_connect_timeout 30

   router_id LVS_DEVEL

}


vrrp_instance VI_1 {

    state master  #定义为主机

    interface eth0

    virtual_router_id 51

    macst_src_ip 192.168.20.137 #主机的IP

    priority 100    #定义优先级

    advert_int 1

    authentication {

        auth_type PASS

        auth_pass 123456

    }

    virtual_ipaddress {

        192.168.20.100  #虚拟的IP,用于访问外网



    }

}

 
6.修改备机的keepalive的配置文件

    vim /etc/keepalived/keepalived.conf

    

global_defs {

   notification_email {

    [email protected]



   }

   notification_email_from root@localhost

   smtp_server 127.0.0.1

   smtp_connect_timeout 30

   router_id LVS_DEVEL

}


vrrp_instance VI_1 {

    state slaver

    interface eth0

    virtual_router_id 51

    macst_src_ip 192.168.20.137

    priority 99

    advert_int 1

    authentication {

        auth_type PASS

        auth_pass 123456

    }

    virtual_ipaddress {

        192.168.20.100



    }

}


7.重启主备机keepalived服务

    service keepalived restart


8.不启动keepalived服务,ping 192.168.20.100是不通的,重启后才能ping通。这个时候虚拟IP就绑定到主机上了。



9.查看tail -f /var/log/message


nginx+keepalive搭配负载均衡_第1张图片

    

nginx+keepalive搭配负载均衡_第2张图片可以看到主备机的日志都已经启动了vrrp虚拟路由冗余协议。


10.通过ip addr查看虚拟IP是否已经绑定在主机上

    nginx+keepalive搭配负载均衡_第3张图片

可以看到已经绑定在主机了。

这样nginx + keepalive的搭建就完成了。


11.通过VIP访问:

http://192.168.20.100/ 发现显示的是主机的IP.

    nginx+keepalive搭配负载均衡_第4张图片

然后在把主机的nginx和keepalived关闭,看是否可以切换到备机

    nginx+keepalive搭配负载均衡_第5张图片


的确可以切换到备机


12.弄个监控脚本来监测nginx的服务,一旦主机的nginx停止掉,会马上停止主机的keepalived,然后切换到备机。

    vim check_nginx.sh

    

#!/bin/bash

#


nginx=`ps -C nginx --no-header | wc -l`


if [ $nginx -eq 0 ]

then

        service nginx restart >> /dev/null

        echo "nginx 已经正常重启工作中"

        sleep 3

else

        echo "nginx 正常运行中..."


        keepalived=`ps -C nginx --no-header | wc -l`


        if [ $keepalived -eq 0 ]

        then

                service keepalived stop >> /dev/null

                echo "已经正常停止keepalived服务"

        else

                echo "keepalived 仍处于运行状态..."

        fi

fi


13.让脚本每隔多久监测一次

    15 * * * * /home/scripts/check_nginx.sh &> /dev/null