使用HAProxy Keepalived实现主备及负载均衡

HAProxy提供高可用性负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,它是免费、快速并且可靠的一种解决方案。根据官方数据,其最高极限支持10G的并发。

HAProxy特别适用于那些负载特大的web站点,这些站点通常又需要会话保持或七层处理。HAProxy运行在当前的硬件上,完全可以支持数以万计的并发连接。并且它的运行模式使得它可以很简单安全的整合进您当前的架构中,同时可以保护你的web服务器不被暴露到网络上。其支持从4层至7层的网络交换,即覆盖所有的TCP协议。就是说,Haproxy甚至还支持Mysql的负载均衡。如果说在功能上,能以proxy反向代理方式实现WEB均衡负载,这样的产品有很多。包括Nginx,ApacheProxy,lighttpd,Cheroke等。但要明确一点的,Haproxy并不是Http服务器。以上提到所有带反向代理均衡负载的产品,都清一色是WEB服务器。简单说,就是他们能自个儿提供静态(html,jpg,gif..)或动态(php,cgi..)文件的传输以及处理。而Haproxy仅仅,而且专门是一款的用于均衡负载的应用代理。其自身并不能提供http服务。开始Haproxy主备高可用测试

测试系统:

  • CentOS6.7/Ubuntu15.04

IP信息:

  • 主Haproxy:192.168.15.132
  • 备Haproxy:192.168.15.133

  • VIP:192.168.15.135(www.test.com/img.test.com)

  • Real1:192.168.15.128

  • Real2:192.168.15.130

  • Real3:192.168.15.140

主LB与备LB均配置

echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf         #开启数据包转发

echo "net.ipv4.ip_nonlocal_bind = 1" >> /etc/sysctl.conf   #允许监听非本地地址

sysctl -p

安装haproxy

cd /usr/local/src

CentOS系统:

yum install wget gcc gcc-c++ autoconf automake make

Ubuntu系统:

sudo apt-get install build-essential  libtool

wget http://pkgs.fedoraproject.org/repo/pkgs/haproxy/haproxy-1.4.24.tar.gz/86422620faa9759907563d5e0524b98c/haproxy-1.4.24.tar.gz

tar -xvzf haproxy-1.4.24.tar.gz

cd haproxy-1.4.24

make TARGET=linux2628 && make install  

#kernel版本大于2.6.28的,使用"TARGET=linux2628",否则使用"TARGET=linux26"。

添加haproxy用户:

useradd -d /var/lib/haproxy -s /bin/false haproxy

创建配置文件

mkdir -p /etc/haproxy 

cp -r  /usr/local/src/haproxy-1.4.24/examples/errorfiles  /etc/haproxy/errorfiles

cp /usr/src/haproxy-1.4.24/examples/haproxy.cfg /etc/haproxy  #拷贝示例文件

cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak      #备份示例文件

负载均衡①:

vi /etc/haproxy/haproxy.cfg
global
        log 127.0.0.1   local0
        log 127.0.0.1   local1 notice
        maxconn 5000
        chroot /var/lib/haproxy
        user haproxy
        group haproxy
        daemon
defaults
        log     global
        mode    http          #所处理的类别 (#7层 http;4层tcp  )
        option  httplog
        option  httpclose
        option  dontlognull   #不记录健康检查的日志信息
        option  forwardfor    #后端服务器需要获得客户端真实ip时配置的参数,可以从Http Header中获得客户端ip
        option  redispatch    #serverId对应的服务器挂掉后,强制定向到其他健康的服务器
        retries 3
        maxconn 4000
        contimeout      8000
        clitimeout      80000
        srvtimeout      80000
listen Web_LB  
      bind *:80
      mode http   #7层:http;4层:tcp
      cookie Web_LB  insert
      balance roundrobin
      option httpclose
      option forwardfor
      #option httpchk GET /index.html #心跳检测的文件
      server Real1 192.168.15.128:80 cookie Real1 check inter 1500 rise 3 fall 3 weight 1
      server Real2 192.168.15.130:80 cookie Real2 check inter 1500 rise 3 fall 3 weight 1
      server Real3 192.168.15.140:80 cookie Real3 check inter 1500 rise 3 fall 3 weight 1
      #服务器定义,"cookie Real1"表示serverid为Real1,"check inter 1500"是检测心跳频率,"rise 3"是3次正确认为服务器可用,"fall 3"是3次失败认为服务器不可用,weight代表权重
      srvtimeout 30000 
listen stats  192.168.15.135:9999
    mode http
    stats enable
    stats refresh 5s
    stats hide-version
    stats realm Haproxy\ Statistics #监控页面提示信息
    stats uri /haproxy-status
    stats auth test:123456
    acl allow src 192.168.15.0/16
    stats admin if TRUE  #手动启用/禁用后端服务器(haproxy-1.4.9以后版本)
    errorfile 403 /etc/haproxy/errorfiles/403.http
    errorfile 500 /etc/haproxy/errorfiles/500.http
    errorfile 502 /etc/haproxy/errorfiles/502.http
    errorfile 503 /etc/haproxy/errorfiles/503.http
    errorfile 504 /etc/haproxy/errorfiles/504.http

负载均衡②:

vi /etc/haproxy/haproxy.cfg
global
        log 127.0.0.1   local0
        log 127.0.0.1   local1 notice
        maxconn 5000
        chroot /var/lib/haproxy
        user haproxy
        group haproxy
        daemon
defaults
        log     global
        mode    http 
        option  httplog
        option  httpclose
        option  dontlognull  
        option  forwardfor   
        option  redispatch   
        retries 3
        maxconn 4000
        contimeout      8000
        clitimeout      80000
        srvtimeout      80000
listen stats  192.168.15.135:9999
    mode http
    stats enable
    stats refresh 5s
    stats hide-version
    stats realm Haproxy\ Statistics 
    stats uri  /haproxy-status
    stats auth test:123456
    acl allow src 192.168.15.0/16
    stats admin if TRUE
frontend www
    bind *:80
    acl web hdr_reg(host) -i ^(www.test.com|test.com)$
    #acl后面是规则名称。如果请求的域名满足正则表达式中的2个域名返回true(-i是忽略大小写),则分发请求至webserver的作用域。
    acl img hdr(host) -i img.test.com
    #如果访问img.test.com就分发到imgserver这个作用域。
    use_backend webserver if web
    use_backend imgserver if img
    default_backend webserver

backend webserver
    mode http
    balance roundrobin               #默认的负载均衡方式
    #balance source                  #类似Nginx的ip_hash,balance source 保存session值
    #balance leastconn               #最小连接
    cookie  SERVERID insert indirect
    option  httpchk /index.php   
    server Real1 192.168.15.128:80 cookie Real1 check inter 1500 rise 3 fall 3 weight 1
    server Real2 192.168.15.130:80 cookie Real2 check inter 1500 rise 3 fall 3 weight 1
    server Real3 192.168.15.140:80 cookie Real3 check inter 1500 rise 3 fall 3 weight 1
    #服务器定义,"cookie Real1"表示serverid为Real1,"check inter 1500"是检测心跳频率,"rise 3"是3次正确认为服务器可用,"fall 3"是3次失败认为服务器不可用,weight代表权重

backend imgserver
    mode http
    balance  roundrobin  
    option  httpchk /index.php
    server Real1 192.168.15.128:80 check inter 1500 rise 3 fall 3 weight 1
    server Real2 192.168.15.130:80 check inter 1500 rise 3 fall 3 weight 1
    server Real3 192.168.15.140:80 check inter 1500 rise 3 fall 3 weight 1

    errorfile 403 /etc/haproxy/errorfiles/403.http
    errorfile 500 /etc/haproxy/errorfiles/500.http
    errorfile 502 /etc/haproxy/errorfiles/502.http
    errorfile 503 /etc/haproxy/errorfiles/503.http
    errorfile 504 /etc/haproxy/errorfiles/504.http

动静分离:

global
        log 127.0.0.1   local0
        log 127.0.0.1   local1 notice
        maxconn 5000
        chroot /var/lib/haproxy
        user haproxy
        group haproxy
        daemon
defaults
        log     global
        mode    http 
        option  httplog
        option  httpclose
        option  dontlognull  
        option  forwardfor   
        option  redispatch   
        retries 3
        maxconn 4000
        contimeout      8000
        clitimeout      80000
        srvtimeout      80000
listen stats  192.168.15.135:9999
    mode http
    stats enable
    stats refresh 5s
    stats hide-version
    stats realm Haproxy\ Statistics 
    stats uri  /haproxy-status
    stats auth test:123456
    acl allow src 192.168.15.0/16
    stats admin if TRUE
frontend  main *:80       #前端代理
    acl url_static     path_beg   -i  /static /images /javascript /stylesheets
    acl url_static     path_end   -i  .jpg .gif .png .css .js
    acl url_dynamic    path_end   -i  .php
    use_backend static_servers    if url_static
    default_backend           dynamic_servers 
backend static_servers   #后端的静态请求响应
    balance     roundrobin
    server      static 192.168.15.128:80 inter 3000 rise 2 fall 3 check maxconn 5000
backend dynamic_servers  #后端的动态请求响应
    balance     roundrobin
    server  dynamic1 192.168.15.130:80 inter 3000 rise 2 fall 3 check maxconn 5000
    server  dynamic2 192.168.15.140:80 inter 3000 rise 2 fall 3 check maxconn 5000

    errorfile 403 /etc/haproxy/errorfiles/403.http
    errorfile 500 /etc/haproxy/errorfiles/500.http
    errorfile 502 /etc/haproxy/errorfiles/502.http
    errorfile 503 /etc/haproxy/errorfiles/503.http
    errorfile 504 /etc/haproxy/errorfiles/504.http

启动haproxy

cp /usr/local/src/haproxy-1.4.24/examples/haproxy.init  /etc/rc.d/init.d/haproxy

chmod +x  /etc/rc.d/init.d/haproxy

chkconfig haproxy on

cp /usr/local/src/haproxy-1.4.24/haproxy /usr/sbin/haproxy

/etc/init.d/haproxy start

设置HAProxy日志

“/etc/rsyslog.d”目录下创建haproxy日志配置文件

local0.=info -/var/log/haproxy.log         #haproxy.log保存http日志

local0.notice -/var/log/haproxy-status.log #haproxy-status.log记录haproxy状态变更

vi /etc/rsyslog.d/haproxy.conf

$ModLoad imudp       #imudp是模块名,支持UDP协议
$UDPServerRun 514   #允许514端口接收使用UDP和TCP协议转发过来的日志,rsyslog在默认情况下在514端口监听UDP
$template Haproxy,"%msg%\n"
local0.=info -/var/log/haproxy.log;Haproxy
local0.notice -/var/log/haproxy-status.log;Haproxy
### keep logs in localhost ##
local0.* ~

vim /etc/sysconfig/rsyslog

SYSLOGD_OPTIONS="-c 2 -r -m 0"
#各参数作用:
#-c 指定运行兼容模式。
#-r 接收远程日志
#-x 在接收客户端消息时,禁用DNS查找。需和-r参数配合使用。
#-m 标记时间戳。单位是分钟,为0时,表示禁用该功能。

重启rsyslog服务

service rsyslog restart

日志轮转配置

vim /etc/logrotate.d/haproxy

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

创建定时任务:

59 23 * * * root /usr/sbin/logrotate -f /etc/logrotate.conf >/dev/null 2>&1
service crond restart

配置keepalived

wget http://www.keepalived.org/software/keepalived-1.2.15.tar.gz

tar -zxvf keepalived-1.2.15.tar.gz

cd keepalived-1.2.15

./configure --sysconf=/etc/  --with-kernel-dir=/usr/src/kernels/2.6.32-573.8.1.el6.x86_64

make && make install

ln -s /usr/local/sbin/keepalived  /sbin/  

配置keepalived.conf:

主:

! Configuration File for keepalived
global_defs {
   notification_email {
    test@163.com
   }
   notification_email_from keepalived@localhost
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id Haprxoy_Master    
}
vrrp_script check_haproxy {
  script "/usr/local/src/check_haproxy.sh"
  interval 4
  weight 2
}
vrrp_instance VI_1 {
 #state MASTER
  state BAKCUP
  nopreempt 
  interface bond0
  smtp_alert
  virtual_router_id 66
  priority 100
  advert_int 1
  authentication {
  auth_type PASS
  auth_pass 1111
 }
 track_script {
  check_haproxy
 }
 virtual_ipaddress {
  192.168.15.135/24 broadcast 192.168.15.255 dev bond0 label bond0:1
 }
}

备:

! Configuration File for keepalived
global_defs {
   notification_email {
     test@163.com
   }
   notification_email_from keepalived@localhost
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id Haprxoy_BACKUP   
}
vrrp_script check_haproxy {
 script "/usr/local/src/check_haproxy.sh"
 interval 4
 weight 2
}
vrrp_instance VI_1 {
  state BACKUP
  interface bond0
  smtp_alert
  virtual_router_id 66
  priority 88
  advert_int 1
  authentication {
  auth_type PASS
  auth_pass 1111
 }
 track_script {
  check_haproxy
 }
 virtual_ipaddress {
  192.168.15.135/24 broadcast 192.168.15.255 dev bond0 label bond0:1
 }
}

为防止haproxy异常关闭导致keepalived不自动切换

#!/bin/bash
if [ $(ps -C haproxy --no-header | wc -l) -eq 0 ]; then
     /etc/init.d/haproxy  start
fi
sleep 3
if [ $(ps -C haproxy --no-header | wc -l) -eq 0 ]; then
       /etc/init.d/keepalived stop
fi

chmod +x /usr/local/src/check_haproxy.sh

Keepalived.conf配置完毕,启动keepalived服务:/etc/init.d/keepalived start

关闭其中任何一个服务,访问正常,测试OK。

遇到的问题:

备机启动报错“Starting proxy LOADBAL: cannot bind socket”,原因为nginx进程占用80端口造成,停止nginx后正常。如果“ip_nonlocal_bind”未设置为1(启动haproxy的时候,允许忽视VIP的存在)也会造成相同问题

启动keepalived后日志出现“didn’t respond to SIGTERM”,需将“interval”时间设置相对较长(同时检查iptables状态)

标签:HAproxy 发布于:2019-11-16 23:52:17