天天看点

Keeplived配置Nginx双机高可用

  一、简介

不管是Keepalived还是Heartbeat做高可用,其高可用,都是站在服务器脚本去说的高可用,而不是服务的角度。

也就是说,如果服务器DOWN机或者网络出现故障,高可用是可以实现自动切换的。如果运行的服务,比如Nginx挂掉

这些高可用软件是意识不到的,需要自己写脚本去实现服务的切换。

二、安装配置Keepalived

复制内容到剪贴板

<code># ./configure # make # make install # cp /usr/local/etc/rc.d/init.d/keepalived /etc/rc.d/init.d/ # cp /usr/local/etc/sysconfig/keepalived /etc/sysconfig/ # cp /usr/local/sbin/keepalived /usr/bin/ # chkconfig --add keepalived  # mkdir /etc/keepalived/ # cp /usr/local/etc/keepalived/keepalived.conf /etc/keepalived/</code>

编辑MASTER的主配置文件(MASTER: 1.1.1.1)

<code># vim /etc/keepalived/keepalived.conf ! Configuration File for keepalived global_defs {    router_id LVS_DEVEL } vrrp_script chk_nginx {         script "/opt/monnginx.sh"         interval 2         weight 2 } vrrp_instance VI_1 {     state MASTER     interface eth0     virtual_router_id 51     priority 100     advert_int 1     authentication {         auth_type PASS         auth_pass mdnginx     }     virtual_ipaddress {         1.1.1.100     }     track_script {         chk_nginx   } }</code>

编辑BACKUP的主配置文件(BACKUP:1.1.1.2)

<code># vim /etc/keepalived/keepalived.conf ! Configuration File for keepalived global_defs {    router_id LVS_DEVEL } vrrp_script chk_nginx {         script "/opt/monnginx.sh"         interval 2         weight 2 } vrrp_instance VI_1 {     state BACKUP     interface eth0     virtual_router_id 51     priority 100     advert_int 1     authentication {         auth_type PASS         auth_pass mdnginx     }     virtual_ipaddress {         1.1.1.100     }     track_script {         chk_nginx   } }</code>

三、启动服务与脚本编写(主机和备机都要执行)

<code># service nginx start # service keepalived start</code>

编写监控Nginx的脚本

<code># vim /opt/monnginx.sh #!/bin/bash # author: honway.liu # date: 2013-03-15 if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then         service nginx start fi sleep 3 if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then         service keepalived stop fi</code>

改进脚本,加上报警功能。

<code># vim /opt/monnginx.sh #!/bin/bash # author: honway.liu # date: 2013-03-15 IPADDR=$(ip addr show eth0|awk '{print $2}' | sed -n 3p) contact=([email protected]) num=${#contact[@]} function email() { for ((i=0;i&lt;num;i++));do         echo "$IPADDR service problem" | mail -s "WARNING" ${contact[i]} -- -f [email protected] done } if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then         service nginx start fi email sleep 3 if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then         service keepalived stop email fi</code>

这里的报警使用的是139邮箱,在139邮箱里面设置有邮件的时候,通知到手机,并且以长短信的方式。

需要开户本机的sendmail服务。'

本文转自 gm100861 51CTO博客,原文链接:http://blog.51cto.com/gm100861/1155549

继续阅读