keepalived+haproxy 实现高可用、负载均衡服务器集群
实验环境:iptables和selinux关闭
前端高可用负载均衡调度主机:vm7 172.25.28.7 vm8 172.25.28.8
后台应用服务器: vm1 172.25.28.1 vm2 172.25.28.4
配置如下:#######################################################################
分别在两台调度主机上面修改/etc/haproxy/haproxy.cf
global
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 4000
user haproxy
group haproxy
daemon
stats socket /var/lib/haproxy/stats
defaults
mode http
log global
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
option redispatch
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
maxconn 3000
listen stats_auth *:8080
stats enable
stats uri /status
stats auth admin:westos
stats refresh 5s
listen www.westos.org *:80
balance roundrobin
server web1 172.25.28.1:80 check weight 3
server web2 172.25.28.4:80 check weight 1
server backup 127.0.0.1:8081 backup
两台调度主机:分别修改/etc/keepalived/keepalived.conf
MASTER节点:
! Configuration File for keepalived
vrrp_script check_haproxy { #使用haproxy_check 脚本对后台服务器做一个健康检查
script "/opt/haproxy_check" #此处目录为脚本的绝对路径
interval 5
weight 2
}
global_defs {
notification_email {
root@localhost
}
notification_email_from [email protected]
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_instance VI_1 {
state MASTER #备机的为BACKUP
interface eth0
virtual_router_id 51
priority 100 #两台主备调度器的值设置必须不一样
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
172.25.28.100 #对外虚拟ip
}
track_script {
check_haproxy
}
}
BACKUP:
! Configuration File for keepalived
vrrp_script check_haproxy {
script "/opt/haproxy_check"
interval 5
weight 2
}
global_defs {
notification_email {
root@localhost
}
notification_email_from [email protected]
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_instance VI_1 {
state BACKUP #注意修改此处
interface eth0
virtual_router_id 51
priority 50 注意修改此处
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
172.25.28.100 #对外虚拟ip
}
track_script {
check_haproxy
}
}
分别在两台调度主机上面操作:
添加检测后台服务器健康状况的脚本:在/etc/keepalived/keepalived.conf 中的对应目录下添加文件/opt/haproxy_check
#!/bin/bash
/etc/init.d/haproxy status &> /dev/null || /etc/init.d/haproxy restart &> /dev/null
if [ $? -ne 0 ];then
/etc/init.d/keepalived stop &> /dev/null
fi
测试:分别在两台后台应用服务器上面开启httpd服务,并写上首页文件。 并且要在安装浏览器的主机的/etc/hosts下面写解析。
1.高可用测试:停止master上的keepalived服务,查看backup是否会接管并且根据脚本会不会自动启动haproxy服务
2.负载均衡测试:访问www.westos.org,看到页面在两个后台服务器上切换表示成功!
3.故障切换测试:任意关闭后台服务器上面的httpd服务,查看是否haproxy可以及时发现故障主机,并且将服务转移到正常节点上来执行。