keepalived配置高可用
一.介紹
編寫指令碼,keepalived是根據返回值判斷的,所以這裡直接grep程序名,能查到返回0,否則返回1
讓keepalived每5秒執行一次指令碼,2次都返回1則認為httpd服務掛掉了,則降低優先順序,釋放vip。
有的部落格例子是指令碼檢測服務有問題,直接關閉keepalived,這樣其實很麻煩,而且當臺機器有多個例項都要高可用,就沒法這麼做了。
二.配置
環境宣告
[web-server-1] 主機名 = host-1 系統 = centos-7.3 地址 = 192.168.2.41 軟體 = keepalived-1.3.5 httpd-2.4.6 [web-server-2] 主機名 = host-2 系統 = centos-7.3 地址 = 192.168.2.150 軟體 = keepalived-1.3.5 httpd-2.4.6
服務配置
1.已經有其他需要高可用服務,可以不安裝,這裡只是做測試
(機器均操作)
yum -y install httpd
systemctl start httpd
yum -y install keepalived
systemctl enable keepalived
2.新增測試檔案
(host-1操作)
echo "one" > /var/www/html/index.html
(host-2操作)
echo "tow" > /var/www/html/index.html
3.建立檢測指令碼
(機器均操作)
vim /etc/keepalived/check_httpd.sh
#!/bin/sh A=`ps -C nginx --no-header |wc -l` if [ $A -eq 0 ] then exit 1 fi
chmod +x /etc/keepalived/check_httpd.sh
4.修改配置檔案如下,多餘的刪除
(host-1操作)
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived global_defs { router_id lb01 } vrrp_script httpd #vrrp指令碼命名 { script "/etc/keepalived/check_httpd.sh" #要執行的指令碼 interval 2 #指令碼指定間隔 weight -40 #優先順序(如果指令碼執行結果為0,並且weight配置的值大於0,則優先順序相應的增加,如果指令碼執行結果非0,並且weight配置的值小於0,則優先順序相應的減少) } vrrp_instance VI_1 { state MASTER interface enp0s8 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 1111 } track_script #呼叫上面定義的檢查指令碼 { httpd } virtual_ipaddress { 192.168.2.99 } }
(host-2操作)
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id lb02
}
vrrp_script httpd
{
script "/etc/keepalived/check_httpd.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP
interface enp0s8
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script
{
httpd
}
virtual_ipaddress {
192.168.2.99
}
}
(機器均操作)
systemctl start keepalived
三.測試
最開始的99報錯,是因為主節點還未執行指令碼檢測,等待10秒將切換。這個時間在生產環境無意是非常長的,可以適當調節短。
四.多例項
每一段vrrp_instrance都是一個,底下的看起來沒什麼不同,但是可以配置指令碼,讓VI_1檢測到nginx有問題後,將10.0.0.3下線
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 150
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.3/24 dev eth0 label eth0:1
}
}
vrrp_instance VI_2 {
state BACKUP
interface eth0
virtual_router_id 52
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.4/24 dev eth0 label eth0:2
}
}
本文版權歸作者所有,歡迎轉載,請務必新增原文連結。