LVS+Keepalived 配置
LVS+Keepalived配置
环境准备
LVS1:192.168.1.1
LVS2:192.168.1.2
MySQL Server1:192.168.1.13
MySQL Server2:192.168.1.11
VIP:192.168.1.100
yum -y install keepalived ipvsadm
vi /etc/keepalived/keepalived.conf ! Configuration File for keepalived global_defs { router_id LVS_DB } vrrp_instance VI_1 { state BACKUP #全部设置为BACKUP,防止脑裂,抢资源 interface eth0 #虚拟IP所在网 virtual_router_id 51 #VRID,相同VRID为一个组,决定多播MAC地址 priority 100 #优先级,另一台改为90 节点不一样 advert_int 1 #检查间隔 authentication { auth_type PASS #认证方式,可以是pass或ha auth_pass 1111 #认证密码 } virtual_ipaddress { 192.168.1.100 #VIP } } virtual_server 192.168.1.100 3306 { delay_loop 6 #服务轮询的时间间隔 lb_algo wrr #加权轮询调度,LVS调度算法 rr|wrr|lc|wlc|lblc|sh|sh lb_kind DR #LVS集群模式 NAT|DR|TUN,其中DR模式要求负载均衡器网卡必须有一块与物理网卡在同一个网段 #nat_mask 255.255.255.0 persistence_timeout 50 #会话保持时间 protocol TCP #健康检查协议 ## Real Server设置,3306就是MySQL连接端口 real_server 192.168.1.13 3306 { weight 3 ##权重 TCP_CHECK { connect_timeout 3 nb_get_retry 3 delay_before_retry 3 connect_port 3306 } } real_server 192.168.1.11 3306 { weight 3 TCP_CHECK { connect_timeout 3 nb_get_retry 3 delay_before_retry 3 connect_port 3306 } } }
配置LVS
编写LVS启动脚本/etc/init.d/realserver
SNS_VIP=192.168.1.100 /etc/rc.d/init.d/functions case "$1" in start) ifconfig lo:0 $SNS_VIP netmask 255.255.255.255 broadcast $SNS_VIP /sbin/route add -host $SNS_VIP dev lo:0 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 sysctl -p >/dev/null 2>&1 echo "RealServer Start OK" ;; stop) ifconfig lo:0 down route del $SNS_VIP >/dev/null 2>&1 echo "0" >/proc/sys/net/ipv4/conf/lo/arp_ignore echo "0" >/proc/sys/net/ipv4/conf/lo/arp_announce echo "0" >/proc/sys/net/ipv4/conf/all/arp_ignore echo "0" >/proc/sys/net/ipv4/conf/all/arp_announce echo "RealServer Stoped" ;; *) echo "Usage: $0 {start|stop}" exit 1 esac exit 0
将lvs脚本加入开机自启动
# chmod +x /etc/init.d/realserver # echo "/etc/init.d/realserver" >> /etc/rc.d/rc.local
分别启动LVS和keepalived
# service realserver start
# service keepalived start
配置iptables
# Generated by iptables-save v1.4.21 on Wed Aug 16 16:57:15 2017 *filter :INPUT ACCEPT [10:716] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [19:3472] -A INPUT -d 224.0.0.0/8 -i em2 -p vrrp -j ACCEPT -A INPUT -s 192.168.1.100/32 -i em2 -p vrrp -j ACCEPT -A OUTPUT -d 224.0.0.0/8 -o em2 -p vrrp -j ACCEPT COMMIT # Completed on Wed Aug 16 16:57:15 2017 # Generated by iptables-save v1.4.21 on Wed Aug 16 16:57:15 2017 *nat :PREROUTING ACCEPT [3159:201889] :INPUT ACCEPT [1934:114711] :OUTPUT ACCEPT [4248:256174] :POSTROUTING ACCEPT [4248:256174] -A PREROUTING -d 192.168.1.0/32 -p tcp -m tcp --dport 3306 -j REDIRECT COMMIT
2.在每台真实服务器上运行
ifconfig lo:0 192.168.1.100(虚拟IP地址) netmask 255.255.255.255 up
vi /etc/sysctl.conf #或者 vi /usr/lib/sysctl.d/00-system.conf #添加如下代码: net.ipv4.ip_forward=1 #重启network服务 systemctl restart network