完整的架构需要两台服务器(角色为dir),分别安装Keepalived工具,目的是实现高可用,但Keepalived本身也有负载均衡功能,所以本次使用可以只安装一台Keepalived。Keepalived内置了ipvsadm的功能,所以不需要安装ipvsadm包,也不用编写和执行lvs_dr脚本。
准备工作
三台机器:
调度器director:
IP:192.168.179.128;安装Keepalived
real server(real1):
IP:192.168.179.129
real server(real2):
IP:192.168.179.130
VIP:192.168.179.140
开始搭建
配置director
yum install -y keepalived
自定义Keepalived配置文件:
vim /etc/keepalived/keepalived.conf
vrrp_instance VI_1 {
#备用服务器上为 BACKUP
state MASTER
#绑定vip的网卡为eno16777736,你的网卡和阿铭的可能不一样,这里需要你改一下
interface eno16777736
virtual_router_id 51
#备用服务器上为90
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 123456
}
virtual_ipaddress {
192.168.179.140
}
}
virtual_server 192.168.179.140 80 {
#(每隔10秒查询realserver状态)
delay_loop 10
#(lvs 算法)
lb_algo wlc
#算法(DR模式)
lb_kind DR
#(同一IP的连接60秒内被分配到同一台realserver)
persistence_timeout 0
#(用TCP协议检查realserver状态)
protocol TCP
real_server 192.168.179.129 80 {
#(权重)
weight 100
TCP_CHECK {
#(10秒无响应超时)
connect_timeout 10
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
real_server 192.168.179.130 80 {
weight 100
TCP_CHECK {
connect_timeout 10
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
}
启动Keepalived服务:
systemctl start keepalived
查看网卡信息:
ip add
查看ipvsadm规则:
ipvsadm -ln
配置real server(两台相同配置)
配置路由转发脚本:
vim /usr/local/sbin/lvs_rs.sh
#/bin/bash
vip=192.168.179.140
#把vip绑定在lo上,是为了实现rs直接把结果返回给客户端
ifconfig lo:0 $vip broadcast $vip netmask 255.255.255.255 up
route add -host $vip lo:0
#以下操作为更改arp内核参数,目的是为了让rs顺利发送mac地址给客户端
#参考文档www.cnblogs.com/lgfeng/archive/2012/10/16/2726308.html
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
sh /usr/local/sbin/lvs_rs.sh
配置完成!
测试
在浏览器访问VIP:192.168.178.140,刷新网页,访问结果由real1、real2交替回复。
Keepalived+LVS作用
Keepalived搭建高可用保证LVS中director宕机后服务器不瘫痪
如果只使用LVS,那么当LVS架构中某个real server宕机后,director仍然会继续向其发送请求,添加Keepalived后会自动将宕机的real server清除出rs列表。
扩展
haproxy+keepalived http://blog.csdn.net/xrt95050/article/details/40926255
nginx、lvs、haproxy比较 http://www.csdn.net/article/2014-07-24/2820837
keepalived中自定义脚本 vrrp_script http://my.oschina.net/hncscwc/blog/158746
lvs dr模式只使用一个公网ip的实现方法 http://storysky.blog.51cto.com/628458/338726