LVS简介
LVS是linux Virtual Server的简写,意即Linux虚拟服务器,是一个虚拟的服务器集群系统。LVS主要用于多服务器的负载均衡。它工作在网络层,可以实现高性能,高可用的服务器集群技术。它是我们国家的章文嵩博士的一个开源项目。在linux内存2.6中,它已经成为内核的一部分,在此之前的内核版本则需要重新编译内核。
#!/bin/bash
# description: Config realserver
LVS_VIP=192.168.20.227
source /etc/rc.d/init.d/functions
case "$1" in
start)
/sbin/ifconfig lo:0 $LVS_VIP netmask 255.255.255.255 broadcast $LVS_VIP
/sbin/route add -host $LVS_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)
/sbin/ifconfig lo:0 down
/sbin/route del $LVS_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
Keepalived的作用是检测服务器的状态,如果有一台web服务器宕机,或工作出现故障,Keepalived将检测到,并将有故障的服务器从系统中剔除,同时使用其他服务器代替该服务器的工作,当服务器工作正常后Keepalived自动将服务器加入到服务器群中,这些工作全部自动完成,不需要人工干涉,需要人工做的只是修复故障的服务器。
yum install keepalived
#Keepalived 相关操作命令
#启动Keepalived
systemctl start keepalived
#关闭Keepalived
systemctl start keepalived
#重启Keepalived
systemctl restart keepalived
#查看状态Keepalived
systemctl status keepalived
编辑vi
/etc/keepalived/keepalived.conf文件,编辑完成后重启keepalived生效
! Configuration File for keepalived
global_defs {
notification_email {
wangzhiyuan@hec.cn
}
#notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.20.229 #本机ip
smtp_connect_timeout 30
router_id LVS_DEVEL_229
vrrp_skip_check_adv_addr
script_user root
enable_script_security
#vrrp_strict
#vrrp_garp_interval 0
#vrrp_gna_interval 0
}
vrrp_script chk_Nginx {
script "/etc/keepalived/nginx_check.sh" #检测nginx进程是否存在脚本
interval 1
}
vrrp_instance VI_1 {
state MASTER/BACKUP #MASTER:主 BACKUP:从
interface ens160 #网卡
virtual_router_id 51 #主从两台配置id需一致
priority 100 #优先级 主优先级设置比从优先级高
advert_int 1
authentication {
auth_type PASS
auth_pass keepnginx #密码 主从两台主机配置需一致
}
virtual_ipaddress {
192.168.20.227 #虚拟ip
}
track_script {
chk_nginx
}
}
virtual_server 192.168.20.227 80 { #lvs负载端口
delay_loop 6
lb_algo wrr #负载均衡算法
lb_kind DR
persistence_timeout 0
protocol TCP
real_server 192.168.20.229 80 { #真实ip及端口
weight 1
TCP_CHECK {
connection_timeout 5
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
real_server 192.168.20.228 80 { #真实ip及端口
weight 1
TCP_CHECK {
connection_timeout 5
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
}
#!/bin/bash
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
serivce keepalived stop
fi