用HAProxy和KeepAlived构建高可用的反向代理系统

作者: JeremyWei | 可以转载, 但必须以超链接形式标明文章原始出处和作者信息及版权声明

网址: http://weizhifeng.net/HA-with-HAProxy-and-KeepAlived.html

前言

对于访问量较大的网站来说,随着流量的增加单台服务器已经无法处理所有的请求,这时候需要多台服务器对大量的请求进行分流处理,即负载均衡。而如果实现负载均衡,必须在网站的入口部署服务器(不只是一台)对这些请求进行分发,这台服务器即反向代理。由于反向代理服务器是网站的入口,其负载压力大且易遭到攻击,存在单点故障的风险,所以我们需要一个高可用的方案来实现当一台反向代理服务器宕机的时候,另一台服务器会自动接管服务。基于以上要求,我们使用HAProxy,KeepAlived来构建高可用的反向代理系统。

介绍

HAProxy是高性能的代理服务器,其可以提供7层和4层代理,具有healthcheck,负载均衡等多种特性,性能卓越,包括Twitter,Reddit,StackOverflow,GitHub在内的多家知名互联网公司在使用。

KeepAlived是一个高可用方案,通过VIP(即虚拟IP)和心跳检测来实现高可用。其原理是存在一组(两台)服务器,分别赋予Master,Backup两个角色,默认情况下Master会绑定VIP到自己的网卡上,对外提供服务。Master,Backup会在一定的时间间隔向对方发送心跳数据包来检测对方的状态,这个时间间隔一般为2秒钟,如果Backup发现Master宕机,那么Backup会发送ARP包到网关,把VIP绑定到自己的网卡,此时Backup对外提供服务,实现自动化的故障转移,当Master恢复的时候会重新接管服务。

环境

OS: CentOS Linux release 6.0 (Final) 2.6.32-71.29.1.el6.x86_64
HAProxy: 1.4.18
KeepAlived: 1.2.2
VIP: 192.168.1.99
M: 192.168.1.222
S: 192.168.1.189

架构

                    192.168.1.99
             +-----------VIP----------+
             |                        |
             |                        |
           Master                   Backup
        192.168.1.189            192.168.1.222
        +----------+             +----------+
        | HAProxy  |             | HAProxy  |
        |keepalived|             |keepalived|
        +----------+             +----------+
             |
             v
    +--------+---------+
    |        |         |
    |        |         |
    v        v         v
+------+  +------+  +------+
| WEB1 |  | WEB2 |  | WEB3 |
+------+  +------+  +------+

安装HAProxy

安装pcre

yum install pcre
wget http://haproxy.1wt.eu/download/1.4/src/haproxy-1.4.18.tar.gz
tar -zxvf haproxy-1.4.18.tar.gz
cd haproxy-1.4.18
make TARGET=linux26 ARCH=x86_64 USE_PCRE=1 CPU=native
make install

配置文件

/etc/haproxy.cfg

global
    log 127.0.0.1 local3 # 日志
    maxconn 20000
    #uid 500             # uid和gid按照实际情况进行配置
    #gid 500
    chroot /var/chroot/haproxy
    user haproxy
    group haproxy
    daemon               # 以后台方式运行
    nbproc 1             # haproxy的进程数

defaults
   log     127.0.0.1       local3
   mode    http
   option  httplog
   option  httpclose
   option  dontlognull
   option  forwardfor
   option  redispatch
   retries 2
   maxcon  65535
   balance roundrobin   # 简单轮循
   stats   uri     /haproxy-stats
   contimeout      5000
   clitimeout      50000
   srvtimeout      50000

frontend http-in
        bind *:80
        default_backend pool1

backend pool1
        option httpchk HEAD / HTTP/1.0
        stats refresh 2
        server WEB1 192.168.1.189:81 weight 3 maxconn 10000 check
        server WEB2 192.168.1.222:81 weight 3 maxconn 10000 check

# 这是另一种配置方式?
# 这里也要注意千万不要绑定VIP地址,只有主keepalived才会拥有VIP
listen web_vip 0.0.0.0:80
    mode http
    option httplog
    log global
    # 在三台web服务器建立index.html以便健康检查,为区分内容分别设为:129:80,130:8080,131:8080
    option httpchk HEAD /index.html HTTP/1.0
    server web1  192.168.207.129:80   weight 5  check inter 2000 rise 2 fall 3
    server web2  192.168.207.130:8080 weight 5  check inter 2000 rise 2 fall 3
    server web3  192.168.207.131:8080 weight 5  check inter 2000 rise 2 fall 3

日志

haproxy会把日志记录发送到syslog server(CentOS6下是rsyslogd,UDP514端口), 编辑/etc/rsyslog.conf文件,添加如下内容:

$ModLoad imudp
$UDPServerRun 514
$UDPServerAddress 127.0.0.1
local3.*                /var/log/haproxy.log
/etc/init.d/rsyslog restart

编辑/etc/logrotate.d/haproxy.cfg,添加如下内容:

/var/log/haproxy.log
{
    rotate 4
    daily
    missingok
    notifempty
    compress
    delaycompress
    sharedscripts
    postrotate
    reload rsyslog > /dev/null 2>&1 || true
    endscript
}

安装KeepAlived

安装依赖库

yum install popt popt-devel

安装KeepAlived

wget http://www.keepalived.org/software/keepalived-1.2.2.tar.gz
tar -zxvf keepalived-1.2.2.tar.gz
cd keepalived-1.2.2
./configure --prefix=/usr/local/keepalived
make && make install

cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/keepalived
cp /usr/local/keepalived/sbin/keepalived /usr/sbin/
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
mkdir -p /etc/keepalived/
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf
chmod +x /etc/init.d/keepalived

使用方式

/etc/init.d/keepalived start|stop|restart
global_defs {

   notification_email {
       user@example.com
   }

   notification_email_from mail@example.org
   smtp_server 192.168.x.x
   smtp_connect_timeout 30
   router_id LVS_DEVEL
}

#监测haproxy进程状态,每2秒执行一次
vrrp_script chk_haproxy {
    script "/usr/local/keepalived/chk_haproxy.sh"
    interval 2
    weight 2
}

vrrp_instance VI_1 {
    state MASTER #标示状态为MASTER
    interface eth0
    virtual_router_id 51
    priority 101   #MASTER权重要高于BACKUP
    advert_int 1
    mcast_src_ip 192.168.1.189 #Master服务器IP

    authentication {
        auth_type PASS #主从服务器验证方式
        auth_pass 1111
    }

    track_script {
        chk_haproxy #监测haproxy进程状态
    }

    #VIP
    virtual_ipaddress {
        192.168.1.99 #虚拟IP
    }
}
    state BACKUP  #状态为BACKUP
    priority 100  #权重要低于MASTER
#!/bin/bash
#
# author: weizhifeng
# description:
# 定时查看haproxy是否存在,如果不存在则启动haproxy,
# 如果启动失败,则停止keepalived
#
status=$(ps aux|grep haproxy | grep -v grep | grep -v bash | wc -l)
if [ "${status}" = "0" ]; then
    /etc/init.d/haproxy start

    status2=$(ps aux|grep haproxy | grep -v grep | grep -v bash |wc -l)

    if [ "${status2}" = "0"  ]; then
            /etc/init.d/keepalived stop
    fi
fi

高可用测试

在Master上停止keepalived,查看系统日志,发现MASTER释放了VIP

/etc/init.d/keepalived stop
tail -f /var/log/message

Keepalived: Terminating on signal Keepalived: Stopping Keepalived v1.2.2 (11/03,2011)
Keepalived_vrrp: Terminating VRRP child process on signal
Keepalived_vrrp: VRRP_Instance(VI_1) removing protocol VIPs.

在Backup上查看系统日志,发现Backup已经进入MASTER角色,并且绑定了VIP 192.168.1.99

tail -f /var/log/message

Keepalived_vrrp: VRRP_Instance(VI_1) Entering MASTER STATE
Keepalived_vrrp: VRRP_Instance(VI_1) setting protocol VIPs
Keepalived_vrrp: VRRP_Instance(VI_1) Sending gratuitous ARPs on eth0 for 192.168.1.99 #在Backup上查看VIP是否已经绑定

在Master上重新启动keepalived,查看系统日志,发现重新获得MASTER角色,并且绑定VIP 192.168.1.99

tail -f /var/log/message
/etc/init.d/keepalived start
tail -f /var/log/message

Keepalived_vrrp: VRRP_Instance(VI_1) Transition to MASTER STATE
Keepalived_vrrp: VRRP_Instance(VI_1) Entering MASTER STATE
Keepalived_vrrp: VRRP_Instance(VI_1) setting protocol VIPs.
Keepalived_vrrp: VRRP_Instance(VI_1) Sending gratuitous ARPs on eth0 for 192.168.1.99

在Backup上查看系统日志,发现其重新回到BACKUP角色,并且释放VIP

tail -f /var/log/message
Keepalived_vrrp: VRRP_Instance(VI_1) Received higher prio advert
Keepalived_vrrp: VRRP_Instance(VI_1) Entering BACKUP STATE
Keepalived_vrrp: VRRP_Instance(VI_1) removing protocol VIPs.

并发测试

我们使用webbench来对HAProxy进行并发测试

yum install ctags
wget http://home.tiscali.cz/~cz210552/distfiles/webbench-1.5.tar.gz
tar -zxvf webbench-1.5.tar.gz
cd webbench-1.5
make
mkdir -p /usr/local/man && make install
CPU:Intel 双核 x86_64 主频3191MHZ
Mem:2G
pm.start_servers = 100
pm.max_spare_servers = 100

并发访问txt文件,HAProxy的session数量为10000左右,这说明HAProxy能够hold住10000个并发连接;

并发访问php文件,HAProxy的session峰值为200左右,接近于后端PHP的并发处理能力(100x2)。

参考:

http://haproxy.1wt.eu/download/1.4/doc/configuration.txt

http://kevin.vanzonneveld.net/techblog/article/haproxy_logging/