下載下傳 keepalived——rpm包位址:
http://www.rpm-find.net/linux/RPM/ftp.scientificlinux.org/linux/scientific/6.4/x86_64/os/Packages/keepalived-1.2.7-3.el6.x86_64.html
配好yum倉庫解決
yum -y install keepalived-1.2.7-3.el6.x86_64.rpm
#安裝keepalived包
[[email protected] data]# rpm -aq keepalived
keepalived-1.2.7-3.el6.x86_64
[[email protected] data]# /etc/init.d/keepalived start
正在啟動 keepalived: [确定]
[[email protected] data]# ps -el | grep keep
1 S root 4153 1 0 80 0 - 27526 poll_s 23:38 ? 00:00:00 /usr/sbin/keepalived -D
1 S root 4155 4153 0 80 0 - 28052 poll_s 23:38 ? 00:00:00 /usr/sbin/keepalived -D
5 S root 4156 4153 0 80 0 - 28052 poll_s 23:38 ? 00:00:00 /usr/sbin/keepalived -D
啟動後有3個keepalived程序表示安裝正确
[[email protected] data]# ip add | grep 192.168
inet 192.168.227.11/24 brd 192.168.227.255 scope global eth0
inet 192.168.200.16/32 scope global eth0
inet 192.168.200.17/32 scope global eth0
inet 192.168.200.18/32 scope global eth0
預設有三個vip位址
主配置檔案
vim /etc/keepalived/keepalived.conf
修改主配置檔案
1 ! Configuration File for keepalived
2
3 global_defs {
4 notification_email {
5 [email protected]
6 [email protected]
7 [email protected]
8 }
9 notification_email_from [email protected]
10 smtp_server 192.168.200.1
11 smtp_connect_timeout 30 #11行以前是keepalive的郵件報警設定,預設即可
12 router_id ningx01 #唯一辨別符,主節點與備節點的router_id不能相同
13 }
14
15 vrrp_script chk_nginx { #定義vrrp腳本,名稱chk_nginx
16 script "/data/chk_nginx.py" #腳本的路徑,腳本内容見後方
17
18 interval 2 #間隔2秒
19 weight 2 #權重2次
20 }
21
22 vrrp_instance VI_1 { #vrrp執行個體,執行個體名為VI_1,主備節點的名稱應該相同
23 state MASTER #身份master
24 interface eth0 #通信接口eth0
25 virtual_router_id 55 #虛拟路由ID,在配置檔案中應該唯一
26 priority 150 #優先級,數值越大優先級越高,間隔建議相差50
27 advert_int 1 #通信間隔默1秒
28 authentication { #權限配置
29 auth_type PASS #使用PASS認證,主備節點相同
30 auth_pass 1111 #認證密碼,主備相同
31 }
32 virtual_ipaddress { #虛拟IP位址
33 192.168.227.10/24 dev eth0 label eth0:1#vip192.168.227.10,子網路遮罩24位,綁定接口eth0,别名eth0:1 ,主備相同
34 }
35 track_script { #觸發檢測
36 chk_nginx #檢測的腳本名為chk_nginx,前面定義的名稱
37 }
38 }
前11行為設定報警郵件的設定,預設即可,報警郵件可用zabbix
[[email protected] data]# /etc/init.d/keepalived restart
停止 keepalived: [确定]
正在啟動 keepalived: [确定]
重新開機服務
[[email protected] data]# ip add | grep eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
inet 192.168.227.11/24 brd 192.168.227.255 scope global eth0
inet 192.168.227.10/24 scope global secondary eth0:1
檢查192.168.227.10的VIP已經出現
backup的配置檔案和master的一樣,除下表的内容外
Keepalived配置參數 Master節點Backup節點
Router_id(唯一辨別) router_id lb01router_id lb02
State(角色狀态) state MASTERstate BACKUP
Priority(優先級) priority 150priority 100
nginx服務挂了,自動關閉keepalived,
自動關閉keepalived服務腳本
[[email protected] data]# cat chk_nginx.py
#!/usr/bin/env python
import commands
state,valu = commands.getstatusoutput("netstat -atupn | grep nginx | grep LISTEN| wc -l")
if valu == "0":
print "ooo"
commands.getstatusoutput("service keepalived stop")