Keepalived+Haproxy实现高可用负载均衡

时间:2022-06-24 22:47:49

高可用负载(主备节点)部署步骤

完成下图一个简单的高可用负载机制:

Keepalived+Haproxy实现高可用负载均衡

1.拷贝keepalived-1.2.19.tar.gz至Linux的/home目录(也可以是其它目录)

2.解压并安装keepalived:

tar -zxvf keepalived-1.2.19.tar.gz
yum install popt-devel
yum -y install openssl-devel
cd keepalived-1.2.19
./configure
make && make install

这样keepalived编译及安装完成!

3.拷贝并复制keepalived:

cp /usr/local/etc/rc.d/init.d/keepalived /etc/rc.d/init.d/
cp /usr/local/etc/sysconfig/keepalived /etc/sysconfig/
mkdir /etc/keepalived
cp /usr/local/etc/keepalived/keepalived.conf /etc/keepalived/
cp /usr/local/sbin/keepalived /usr/sbin/

上传并覆盖keepalived.conf至/etc/keepalived
备注:keepalived.conf详见步骤4

上传check_haproxy.sh至/etc/keepalived
备注:check_haproxy.sh配置文件内容如下:

#!/bin/bash
A=`ps -C haproxy --no-header |wc -l`
if [ $A -eq 0 ];then
/usr/local/haproxy/sbin/haproxy -f /usr/local/haproxy/cfg/haproxy.cfg
sleep 3
if [ `ps -C haproxy --no-header |wc -l` -eq 0 ];then
/etc/init.d/keepalived stop
fi
fi

4.修改keepalived.conf配置文件:

! Configuration File for keepalived

global_defs {
notification_email {
receiver@qq.com # 修改成可用的收件人地址,可为多个
}
notification_email_from sender@qq.com # 修改成可用的发件人地址
smtp_server mail.iflytek.com # 修改成可用的邮箱代理地址
smtp_connect_timeout 30
router_id keepalived
}
vrrp_script chk_http_port {
script "/etc/keepalived/check_haproxy.sh" # 修改成Haproxy监控脚本路径
interval 2 # 检查间隔时间,单位:秒
}
vrrp_instance VI_MASTER {
state MASTER # 修改成MASTER,意味着该服务器为主节点;若修改为BACKUP,则为备用节点,即当主机宕掉,从机接管
interface eth0
virtual_router_id 51
priority 150
nopreempt
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_http_port
}
virtual_ipaddress {
192.168.1.1 # 修改成可用的虚拟IP
}
}

5.解压haproxy-1.5.12并上传至/usr/local

6.修改/usr/local/haproxy/cfg配置文件haproxy.cfg:

global
daemon
nbproc 1
group nobody
user nobody
maxconn 102400
ulimit-n 204821
chroot /usr/local/haproxy

defaults
mode tcp
maxconn 102400
retries 3
option redispatch
option abortonclose
timeout connect 600s
timeout client 600s
timeout server 600s

listen interface
bind 0.0.0.0:8001
balance leastconn
mode http
server interface1 192.168.85.100:8001 weight 1 maxconn 102400 check inter 10s
server interface2 192.168.85.101:8001 weight 1 maxconn 102400 check inter 10s

listen engine
bind 0.0.0.0:18006
balance leastconn
mode tcp
server engine1 192.168.85.100:18006 weight 1 maxconn 102400 check inter 10s
server engine2 192.168.85.101:18006 weight 1 maxconn 102400 check inter 10s

至此完成Haproxy配置修改!

7.运行如下命令,启动Haproxy运行:

/etc/init.d/keepalived start

8.测试:

telnet 192.168.1.1 8001
telnet 192.168.1.1 18006

依次使用虚拟IP+路由端口的形式验证对应端口是否可用!

说明:对于从机部署,与主机部署一致。这里说明一下:对于HA,只会使用主节点,仅当主节点挂掉,才会切换到从节点!