nginx使用keepalived实现高可用

环境:

主:linux-node1  110.0.0.137
备:linux-node2  110.0.0.138
 
VIP: 110.0.0.120
 

NGINX安装:

# yum install nginx
 

1.安装keepalived

 
<pre><code>
# yum -y install kernel-devel make gcc openssl-devel  libnl* popt*

# yum install -y openssl openssl-devel

# tar zxf keepalived-1.2.2.tar.gz 
# cd keepalived-1.2.2
# ./configure  --prefix=/usr/local/keepalived
# make && make install
# cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/
# cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
/bin/cp /usr/local/etc/keepalived/keepalived.conf /etc/keepalived/    
# chmod +x /etc/init.d/keepalived
# mkdir /etc/keepalived
# /bin/cp /usr/local/sbin/keepalived /usr/sbin/
# ll /usr/sbin/
 
</code></pre>
 

2.配置keepalived

2.1.配置主nginx(linux-node1)
 
 
[root@linux-node1 ~]# cat /etc/keepalived/keepalived.conf 
! Configuration File for keepalived
 
global_defs {
   notification_email {
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL
}
vrrp_script chk_http_port {
script "/opt/nginx_pid.sh"
interval 2
weight 2
}
 
vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    mcast_src_ip 110.0.0.137
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
chk_http_port
    }
    virtual_ipaddress {
        110.0.0.120
    }
}
 
2.2.配置从nginx(linux-node2)
[root@linux-node2 keepalived]# cat /etc/keepalived/keepalived.conf 
! Configuration File for keepalived
 
global_defs {
   notification_email {
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL
}
vrrp_script chk_http_port {
script "/opt/nginx_pid.sh"
interval 2
weight 2
}
 
vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 51
    mcast_src_ip 110.0.0.138
    priority 99
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
chk_http_port
    }
    virtual_ipaddress {
        110.0.0.120
    }
}
 

3.编写nginx检查脚本(主备都需要):

 
#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ];then
/etc/init.d/nginx start 
sleep 3
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
/etc/init.d/keepalived stop
fi
fi
 

4.启动nginx和keepalived

/etc/init.d/nginx start
/etc/init.d/keepalived start
 

5.检查虚拟化IP 是否绑定成功

主节点:
可以看到vip 110.0.0.120 已经绑定到主的nginx服务器上了。
 

6.测试:

停止nginx
# /etc/init.d/nginx stop
发现主的nginx无法停止,因为/opt/nginx_pid.sh  会检查nginx状态,如果nginx停止了,那么这个脚本就会自动启动nginx。如果nginx启动失败,那么会立刻停止keepalived,把vip转移到backup  nginx上面
 
我们把nginx的配置文件设置错误,然后停止nginx,这个主的nginx就无法启动了。
检查主nginx机器ip状态:
 
检查backup nginx主机状态:
看到VIP已经转移到backup主机上了。
 
 





posted @ 2016-06-10 23:55  unixfbi.com  阅读(382)  评论(0编辑  收藏  举报