基於keepalived+nginx+lvs的負載均衡的實現(DR模式)
LVS結合keepalive
LVS可以實現負載均衡,但是不能夠進行健康檢查,比如一個rs出現故障,LVS 仍然會把請求轉發給故障的rs伺服器,這樣就會導致請求的無效性。keepalive 軟體可以進行健康檢查,而且能同時實現 LVS 的高可用性,解決 LVS 單點故障的問題,其實 keepalive 就是為 LVS 而生的。
1、實驗環境
4臺節點
Keepalived1 + lvs1(Director1):10.0.172.190
Keepalived2 + lvs2(Director2):10.0.172.193
Real server1:10.0.172.191
Real server2:10.0.172.192
VIP: 10.0.172.209
2、安裝系統軟體
在director1和director2上安裝ipvsadm和keepalived
# yum install ipvsadm keepalived -y
Real server + nginx服務的2個節點安裝
# yum install epel-release -y
# yum install nginx -y
3、設定配置指令碼
Real server節點2臺配置指令碼:
vim /usr/local/sbin/lvs_dr_rs.sh #! /bin/bash vip=192.168.0.38 ifconfig lo:0 $vip broadcast $vip netmask 255.255.255.255 up route add -host $vip lo:0 echo "1" >/proc/sys/net/ipv4/conf/lo/arp_ignore echo "2" >/proc/sys/net/ipv4/conf/lo/arp_announce echo "1" >/proc/sys/net/ipv4/conf/all/arp_ignore echo "2" >/proc/sys/net/ipv4/conf/all/arp_announce
2節點rs 上分別執行指令碼:
bash /usr/local/sbin/lvs_dr_rs.sh
keepalived節點配置(2節點):
主節點( MASTER )配置檔案
vim /etc/keepalived/keepalived.conf vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 10.0.172.209 } } virtual_server 10.0.172.209 80 { delay_loop 6 lb_algo rr lb_kind DR persistence_timeout 0 protocol TCP real_server 10.0.172.191 80 { weight 1 TCP_CHECK { connect_timeout 10 nb_get_retry 3 delay_before_retry 3 connect_port 80 } } real_server 10.0,。172.192 80 { weight 1 TCP_CHECK { connect_timeout 10 nb_get_retry 3 delay_before_retry 3 connect_port 80 } } }
從節點( BACKUP )配置檔案
拷貝主節點的配置檔案keepalived.conf:
scp /etc/keepalived/keepalived.conf [email protected]:/etc/keepalived/keepalived.conf
然後修改如下內容:
state MASTER -> state BACKUP
priority 100 -> priority 90
keepalived的2個節點執行如下命令,開啟轉發功能:
echo 1 > /proc/sys/net/ipv4/ip_forward
4、啟動keepalive
先主後從分別啟動keepalive
service keepalived start
12、驗證結果
實驗1
手動關閉10.0.172.191節點的nginx,service nginx stop 在客戶端上去測試訪問 http://10.0.172.209 結果正常,不會出現訪問191節點,一直訪問的是28節點的內容。
實驗2
手動重新開啟 10.0.172.191節點的nginx, service nginx start 在客戶端上去測試訪問 http://10.0.172.209 結果正常,按照 rr 排程演算法訪問191節點和192節點。
實驗3
測試 keepalived 的HA特性,首先在master上執行命令 ip addr ,可以看到209的vip在master節點上的;這時如果在master上執行 service keepalived stop 命令,這時vip已經不再master上,在slave節點上執行 ip addr 命令可以看到 vip 已經正確漂到slave節點,這時客戶端去訪問 http://10.0.172.209 訪問依然正常,驗證了 keepalived的HA特性。