$ sudo apt-get install ipvsadm keepalived
使用这两个做配合时,无需配置 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 状态
lb_algo wrr # LVS 算法
lb_kind DR # Direct Route
#persistence_timeout 60 # 同一 IP 在 60 秒内分配到同一台 RealServer
protocol TCP # 使用 TCP 协议检查 RealServer 状态
real_server 192.168.1.10 80 {
weight 3 # 权重
TCP_CHECK {
connect_timeout 10 # 10 秒无响应超时
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
}
}
}}
启动 keepalived 服务。
$ sudo service keepalived start
检查 ipvsadm 设置。
$ 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
这时我们就可以用浏览器测试负载效果了。关闭某台 RealServer,会发现请求被转发给其他的 RealServer。重启 "损坏" 的服务器后,负载均衡恢复正常。
(切记检查防火墙设置,我为此郁闷了好长时间)
实验环境: Ubuntu Server 10.04
------------ 分隔线 ------------
其实还应该找一台服务器对 LVS 服务器做热备(参见《Keepalived 双机热备》),如此才是真正高可用方案。