$ sudo apt-get install ipvsadm keepalived
使用這兩個(gè)做配合時(shí),無需配置 ipvsadm,直接修改 keepalived.conf 即可。
$ sudo vim /etc/keepalived/keepalived.conf
global_defs {
router_id LVS_DEVEL
}
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 {
192.168.1.100
}
}
virtual_server 192.168.1.100 80 {
delay_loop 1 # 每隔 1 秒查詢 RealServer 狀態(tài)
lb_algo wrr # LVS 算法
lb_kind DR # Direct Route
#persistence_timeout 60 # 同一 IP 在 60 秒內(nèi)分配到同一臺(tái) RealServer
protocol TCP # 使用 TCP 協(xié)議檢查 RealServer 狀態(tài)
real_server 192.168.1.10 80 {
weight 3 # 權(quán)重
TCP_CHECK {
connect_timeout 10 # 10 秒無響應(yīng)超時(shí)
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
real_server 192.168.1.20 80 {
weight 3
TCP_CHECK {
connect_timeout 10
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
}}
啟動(dòng) keepalived 服務(wù)。
$ sudo service keepalived start
檢查 ipvsadm 設(shè)置。
$ sudo ipvsadm -ln
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP 192.168.1.100:80 wrr
-> 192.168.1.10:80 Route 3 0 0
-> 192.168.1.20:80 Route 3 0 0
在所有 RealServer /etc/rc.local 中添加配置信息后重啟。
$ sudo vim /etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
ifconfig lo:0 192.168.1.100 netmask 255.255.255.255 broadcast 192.168.1.100 up
route add -host 192.168.1.100 dev lo:0
echo "0" > /proc/sys/net/ipv4/ip_forward
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
exit 0
這時(shí)我們就可以用瀏覽器測試負(fù)載效果了。關(guān)閉某臺(tái) RealServer,會(huì)發(fā)現(xiàn)請求被轉(zhuǎn)發(fā)給其他的 RealServer。重啟 "損壞" 的服務(wù)器后,負(fù)載均衡恢復(fù)正常。
(切記檢查防火墻設(shè)置,我為此郁悶了好長時(shí)間)
實(shí)驗(yàn)環(huán)境: Ubuntu Server 10.04
------------ 分隔線 ------------
其實(shí)還應(yīng)該找一臺(tái)服務(wù)器對 LVS 服務(wù)器做熱備(參見《Keepalived 雙機(jī)熱備》),如此才是真正高可用方案。