Keepalived+HAProxy高可用搭建
📅 2015-01-06 | 🖱️
🔖 haproxy
Keepalived实现了一套VRRP协议(虚拟路由协议),这个协议允许服务器可以动态的设置IP路由。 使用Keepalived可以加强负载均衡软件的可用性。
环境信息 #
1192.168.61.3 ha1 - MASTER
2192.168.61.4 ha2 - BACKUP
Keepalived编译安装 #
1yum -y install openssl-devel
2
3wget http://www.keepalived.org/software/keepalived-<version>.tar.gz
4tar -zxvf keepalived-<version>.tar.gz
5cd keepalived-<version>
6./configure --prefix=/usr/local/keepalived
7
8make
9make install
安装psmisc #
安装psmisc,可使用 killall -0 haproxy
检查haproxy实例是否存活,性能高于ps。
1yum install -y psmisc
配置 #
编辑配置文件/usr/local/keepalived/etc/keepalived/keepalived.conf:
1! Configuration File for keepalived
2
3global_defs {
4 router_id LVS_DEVEL
5}
6
7vrrp_script chk_haproxy {
8 script "/usr/bin/killall -0 haproxy"
9 interval 2
10 weight 2
11}
12
13vrrp_instance VI_1 {
14 state MASTER
15 interface eth0
16 virtual_router_id 51
17 priority 100
18 advert_int 1
19 virtual_ipaddress {
20 192.168.61.2
21 }
22 track_script {
23 chk_haproxy
24 }
25}
配置文件关键配置如下:
vrrp_script chk_haproxy
Haproxy健康检查script "/usr/bin/killall -0 haproxy"
检查haproxy是否存活interval 2
脚本运行周期weight 2
每次检查加权权重vrrp_instance VI_1
虚拟路由配置state MASTER
本机实例状态,备机配置文件中填写BACKUPinterface eth0
本机网卡名称virtual_router_id
虚拟路由编号,主机和备机要保持一致priority 100
本机初始权重,备机填写小雨主机的权重值advert_int
争抢虚拟地址的周期,单位秒virtual_ipaddress
虚拟IP地址,主备机保持一致track_script
对应的健康检查
启动keepalived #
注册为系统服务/usr/lib/systemd/system/keepalived.service:
1[Unit]
2Description=LVS and VRRP High Availability Monitor
3After=syslog.target network-online.target
4
5[Service]
6Type=simple
7PIDFile=/var/run/keepalived.pid
8KillMode=process
9EnvironmentFile=-/usr/local/keepalived/etc/sysconfig/keepalived
10ExecStart=/usr/local/keepalived/sbin/keepalived -f /usr/local/keepalived/etc/keepalived/keepalived.conf $KEEPALIVED_OPTIONS
11ExecReload=/bin/kill -HUP $MAINPID
12
13[Install]
14WantedBy=multi-user.target
接下来启动keepalived:
1systemctl enable keepalived
2systemctl start keepalived
测试 #
在ha1上查看网卡eth0
1ip addr sh eth0
22: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
3 link/ether 08:00:27:68:cc:c1 brd ff:ff:ff:ff:ff:ff
4 inet 192.168.61.3/24 brd 192.168.61.255 scope global enp0s8
5 valid_lft forever preferred_lft forever
6 inet 192.168.61.2/32 scope global enp0s8
7 valid_lft forever preferred_lft forever
8 inet6 fe80::a00:27ff:fe68:ccc1/64 scope link
9 valid_lft forever preferred_lft forever
可以看到目前虚IP被ha1持有。
在ha2上查看:
1ip addr sh eth0
22: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
3 link/ether 08:00:27:68:cc:c1 brd ff:ff:ff:ff:ff:ff
4 inet 192.168.61.4/24 brd 192.168.61.255 scope global enp0s8
5 valid_lft forever preferred_lft forever
6 inet6 fe80::a00:27ff:fe68:ccc1/64 scope link tentative dadfailed
7 valid_lft forever preferred_lft forever
ha2没有持有虚IP。
通过虚IP测试haproxy服务:
1curl 192.168.61.2
2Hello
停止ha1上的haproxy,一会虚IP会漂移到ha2上。