lvs是一个开源免费的负载均衡软件,能实现多台服务器之间的负载均衡,搭配heartbeat和ldirectord的使用,就能配置成高可用的集群。
服务器环境说明
下面说明本次测试配置的服务器环境。
系统:CentOS-5 32 内核2.6.18-238.el5
因为机器只有两台,所以lvs负载器和后端服务器在同一机器。
node1 192.168.79.130
node2 192.168.79.131
VIP 192.168.79.135
当node1出现故障时,lvs负载器和web服务器转移到node2。
如果机器充足,还是建议lvs负载器和web服务器分开。
软件安装
- yum -y install heartbeat heartbeat-ldirectord ipvsadm
配置
主要的配置文件有以下几个:
Authkeys
ha.cf
ldirectord.cf
haresources
authkeys
代码:
ha.cf
- debugfile /var/log/ha-debug
- logfile /var/log/ha-log
- logfacility local0
- keepalive 8
- deadtime 60
- warntime 60
- initdead 120
- udpport 694
- ucast eth0 192.168.79.131
- auto_failback on
- node node1
- node node2
- respawn hacluster /usr/lib/heartbeat/ipfail
- apiauth ipfail gid=haclient uid=hacluster
node2唯一不同是ucast eth0 192.168.79.131,把IP改成node1的IP。
haresources
填入:
- node1 lvs IPaddr::192.168.79.135/24/eth0:0 ldirectord
这段代码的意思是双机启动heartbeat时,启动node1的lvs脚本,接着配置vip 192.168.79.135/24/eth0:0,然后启动ldirectord来设置node1成lvs负载器并监控80端口。如果node1出故障,node1的heartbeat将从右到左停止服务,如先停止ldirectord,取消vip等。接着node2将接管node1的所有服务,如vip,web服务等。
ldirectord.cf
- vi /etc/ha.d/ldirectord.cf
- checktimeout=10
- checkinterval=8
- autoreload=yes
- logfile="/var/log/ldirectord.log"
- logfile="local0"
- quiescent=no
-
- virtual=192.168.79.135:80
- real=192.168.79.130:80 gate
- real=192.168.79.131:80 gate
- service=http
- scheduler=wrr
- persistent=30
- protocol=tcp
- checktype=negotiate
- checkport=80
node2配置这文件时,需要把real=192.168.79.130:80 gate删除,因为当lvs负载器转移到node2时,不能把故障机node1添加到虚拟机。
test.html
在网站根目录建立test.html,并写入Test Page字段,这个用来监控web服务器的健康情况。假设根目录为/var/www/html:
- echo "Test Page" > /var/www/html/test.html
lvs启动脚本
node1上的lvs启动脚本:
- #!/bin/bash
- /sbin/ipvsadm --set 10 10 10
node1上的lvs启动脚本:
- #!/bin/bash
- VIP=192.168.79.135
- /etc/rc.d/init.d/functions
- /sbin/ipvsadm --set 10 10 10
- case "$1" in
- start)
- /sbin/ifconfig lo:0 down
- /sbin/ifconfig eth0:0 $VIP broadcast $VIP netmask 255.255.255.255 up
- /sbin/route add -host $VIP dev eth0:0
- ;;
- stop)
- /sbin/ifconfig eth0:0 down
- /sbin/ifconfig lo:0 $VIP broadcast $VIP netmask 255.255.255.255 up
- /sbin/route add -host $VIP dev lo:0
- ;;
- *)
- echo "Usage: $0 {start|stop}"
- exit 1
- esac
最后加上执行权限:
主机名及hosts配置
1、对两台机分别设置对应的主机名
192.168.79.130 为 node1
192.168.79.131 为 node2
2、添加主机名解析
- 192.168.79.130 node1
- 192.168.79.131 node2
解决arp问题
- net.ipv4.ip_forward = 1
- net.ipv4.conf.lo.arp_ignore = 1
- net.ipv4.conf.lo.arp_announce = 2
- net.ipv4.conf.all.arp_ignore = 1
- net.ipv4.conf.all.arp_announce = 2
立即使内核参数生效:
lvs测试
测试负载均衡:可以在两台机放入不同的首页内容,在不同的客户端测试是否显示不一样的内容
测试高可用:关掉node1 heartbeat,在node2执行ip a查看是否已经接管vip。
测试ldirectord:ldirectord可以实时监控指定的服务是否可用,如果发现不可用,就会使用ipvsadm把这台故障的机从虚拟机中删除。