主nginx負載均衡器 192.168.166.203
輔nginx負載均衡器 192.168.166.177
VIP地址 192.168.166.178
tar -zxvf keepalived-1.2.1.tar.gz
cd keepalived-1.2.1
./configure --prefix=/usr/local/keepalived --sysconf=/etc
cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/rc.d/init.d/
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
cp /usr/local/keepalived/sbin/keepalived /bin/
chkconfig --add keepalived
chmod 755 /etc/init.d/keepalived
chkconfig keepalived on
service keepalived start
MASTER
vim /etc/keepalived/keepalived.conf
smtp_server xxx.smtp.com
smtp_connect_timeout 30
router_id LVS_DEVEL
}
script "/root/monitor_nginx.sh"
interval 2
weight 2
}
state MASTER #(主機爲MASTER,備用機爲BACKUP)
interface eth0 #(HA監測網絡接口)
virtual_router_id 61 #(主、備機的virtual_router_id必須相同)
#mcast_src_ip 192.168.166.203 #(多播的源IP,設置爲本機外網IP,與VIP同一網卡)此項可不設置
priority 90 #(主、備機取不同的優先級,主機值較大,備份機值較小,值越大優先級越高)
advert_int 1 #(VRRP Multicast廣播週期秒數)
authentication {
auth_type PASS #(VRRP認證方式)
auth_pass 1234 #(密碼)
}
track_script {
Monitor_Nginx #(調用nginx進程檢測腳本)
}
virtual_ipaddress {
192.168.166.178 #(VRRP HA虛擬地址)
}
}
###BACKUP方面只需要修改state爲BACKUP , priority比MASTER稍低就OK了
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
service keepalived start
或
/usr/local/keepalived/sbin/keepalived -D -f /etc/keepalived/keepalived.conf
2. 停止其中一個web看是否能將訪問轉到另一臺上
3. 停止兩臺nginx上任何一個nginx進程看監控進程腳本是否會自動啓動nginx
4. 停止任何一臺nginx上的keepalived進程看另一臺是否接管vip
track_interface的意思是將Linux中你想監控的網絡接口卡監控起來,當其中的一塊出現故障是keepalived都將視爲路由器出現故障。
這裏請注意: virtual_router_id 61,同一組master/backup中,也就是如果你設置了多個VRRP,同一組這個ID必須相同,不然啓動的時候主從都會把VIP給啓動了
即:當真實機192.168.166.177上的keepalived 檢測到 真實機192.168.166.203上的keepalived 不可用時,177上將使用vip:192.168.166.178對外服務並由backup角色轉變爲master
keepalived+nginx實現 HA與負載均衡中keepalived負責實現HA功能,控制VIP(虛擬網絡地址)轉移功能,nginx實現對realserver七層負載均衡功能,nginx提供代理服務和cache功能,DNS服務可以負責前段VIP的負載均衡。
keepalived的配置
192.168.200.1 keepalived配置
! Configuration File for keepalived
global_defs {
notification_email {
[email protected]
}
notification_email_from
[email protected]
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_TEST_YDQ
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 61
priority 150
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.200.101/24 dev eth0 label eth0:0
}
}
vrrp_instance VI_2 {
state BACKUP
interface eth0
virtual_router_id 62
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 2222
}
virtual_ipaddress {
192.168.200.102/24 dev eth0 label eth0:1
}
}
vrrp_instance VI_3 {
state BACKUP
interface eth0
virtual_router_id 63
priority 50
advert_int 1
authentication {
auth_type PASS
auth_pass 3333
}
virtual_ipaddress {
192.168.200.103/24 dev eth0 label eth0:1
}
}