概述
通过 ipvsadm 命令来实现LVS,虽然也能完成相应的功能,但也存在如下的问题:
- 命令行操作和变更,很不方便。
- 配置信息不方便持久化。
- 假设一个 RealServer 宕机或无响应,LVS 仍会将请求转发至后端,导致业务不可用。
- 存在单点问题,如果 LVS 服务器宕机,则全部服务不可用。
keepalived 本身就是为 LVS 而开发的,能够优雅的解决上述问题。
示例配置环境
VIP-192.168.1.100
lb01-192.168.1.101
lb02-192.168.1.102
web01-192.168.1.11
web02-192.168.1.12
lb服务器配置
主节点配置文件
global_defs {
router_id LVS_01 #路由器标识
}
vrrp_instance VI_1 {
state MASTER #初始状态
interface ens33 #工作接口
virtual_router_id 51 #虚拟路由ID
priority 150 #优先级
advert_int 1 #通信频率
authentication {
auth_type PASS
auth_pass 1111 #通信密码
}
virtual_ipaddress {
192.168.1.100/24 #虚拟IP
}
}
# 定义LVS集群服务,可以是IP+PORT;也可以是fwmark 数字,也就是防火墙规则
virtual_server 192.168.1.100 80 {
delay_loop 6
lb_algo rr #算法
lb_kind DR #lvs模式
nat_mask 255.255.255.0
#persistence_timeout 50 # 持久连接超时时间,先注释掉,不然在单台上测试时,全部会被lvs调度到其中一台
protocol TCP # 定义协议
real_server 192.168.1.11 80 { #真实服务器地址
weight 1 # 权重
TCP_CHECK {
connect_timeout 8 # 连接超时时间
nb_get_retry 3 # 尝试次数
delay_before_retry 3 # 每次尝试之间间隔几秒
connect_port 80 # 向哪一个端口检查,如果不指定默认使用上面定义的端口
}
}
real_server 192.168.1.12 80 {
weight 1
TCP_CHECK {
connect_timeout 8
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
}
备节点配置文件
global_defs {
router_id LVS_02
}
vrrp_instance VI_1 {
state BACKUP
interface ens33
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.100/24
}
}
virtual_server 192.168.1.100 80 {
delay_loop 6
lb_algo rr
lb_kind DR
nat_mask 255.255.255.0
#persistence_timeout 50
protocol TCP
real_server 192.168.1.11 80 {
weight 1
TCP_CHECK {
connect_timeout 8
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
real_server 192.168.1.12 80 {
weight 1
TCP_CHECK {
connect_timeout 8
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
}
web服务器配置
ifconfig lo:0 192.168.1.100 broadcast 192.168.1.100 netmask 255.255.255.0 up #配置lo
修改内核参数
cat >>/etc/sysctl.conf<<EOF
net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.lo.arp_ignore = 1
net.ipv4.conf.lo.arp_announce = 2
EOF
sysctl -p
测试(curl 192.168.1.100或者访问网页查看)