首页 > 代码库 > keepalived + haproxy 实现web的高可用负载均衡

keepalived + haproxy 实现web的高可用负载均衡

一、Haproxy简介

    人们熟知的软件负载均衡如LVS、HAProxy,各方面性能不亚于硬件负载均衡,HAProxy提供高可用性、负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,它是免费、快速并且可靠的一种解决方案。HAProxy特别适用于那些负载特大的web站点,这些站点通常又需要会话保持或七层处理。

    HAProxy相比LVS的使用要简单很多,功能方面也很丰富。当前,HAProxy支持两种主要的代理模式:"tcp"也即4层(大多用于邮件服务器、内部协议通信服务器等),和7层(HTTP)。在4层模式 下,HAProxy仅在客户端和服务器之间转发双向流量。7层模式下,HAProxy会分析协议,并且能通过允许、拒绝、交换、增加、修改或者***请求 (request)或者回应(response)里指定内容来控制协议,这种操作要基于特定规则。

    HAProxy的负载均衡算法现在也越来越多了,具体有如下8种:

①roundrobin,表示简单的轮询,这个不多说,这个是负载均衡基本都具备的;

②static-rr,表示根据权重,建议关注;

③leastconn,表示最少连接者先处理,建议关注;

④source,表示根据请求源IP,这个跟Nginx的IP_hash机制类似,我们用其作为解决session问题的一种方法

⑤ri,表示根据请求的URI;

⑥rl_param,表示根据请求的URl参数‘balance url_param‘ requires an URL parameter name;

⑦hdr(name),表示根据HTTP请求头来锁定每一次HTTP请求;

⑧rdp-cookie(name),表示根据据cookie(name)来锁定并哈希每一次TCP请求。


二、拓扑图

    wKiom1QkG1OQoWY1AAFCn0M81LQ823.jpg

三、安装

 1、安装配置haproxy A

[root@90sec ~]# yum -y install haproxy

[root@90sec ~]# cd /etc/haproxy/

[root@90sec haproxy]# cp haproxy.cfg haproxy.cfg.bak    ##备份

[root@90sec haproxy]# vim haproxy.cfg

global        #全局配置

    #    local2.*                       /var/log/haproxy.log

    #

    log         127.0.0.1 local2        #日志功能,要开启日志服务


    chroot      /var/lib/haproxy

    pidfile     /var/run/haproxy.pid

    maxconn     4000

    user        haproxy

    group       haproxy

    daemon                            #让haproxy以守护进程的方式工作于后台


    # turn on stats unix socket

    stats socket /var/lib/haproxy/stats


#---------------------------------------------------------------------

# common defaults that all the ‘listen‘ and ‘backend‘ sections will

# use if not designated in their block

#---------------------------------------------------------------------

defaults

    mode                    http       #指定haproxy的工作模式

    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


#---------------------------------------------------------------------

# main frontend which proxys to the backends

#---------------------------------------------------------------------

listen stats

mode http

bind 0.0.0.0:1080             #绑定端口  

stats enable                  #开启stats功能

stats hide-version            # 隐藏版本号

stats uri  /admin?status      #通过什么样的URL访问

stats realm Haproxy\ Statistics    #认证注释信息

stats auth  90sec:admin            #认证放松(user:passwd)

stats admin if TRUE              #如果认证通过,则赋予权限

acl allow src 192.168.0.0/24     #访问控制

tcp-request content accept if allow

tcp-request content reject

frontend proxy          #前端代理

bind *:80            #监听端口

mode http

log global

option httpclose

option logasap

option dontlognull

capture request  header Host len 20

capture request  header Referer len 60

acl url_static       path_beg       -i /static/images/javascript/stylesheets

acl url_static       path_end       -i .jpg .gif .png .css .js .html

use_backend static_servers if url_static

default_backend dynamic_servers    

backend static_servers     #后端静态web

balance source             #算法调度

server web1 172.16.36.130:80 check maxconn 6000

backend dynamic_servers    #后端动态调度

balance source

server web2 172.16.36.131:80 check maxconn 6000

配置日志

[root@90sec ~]# vim /etc/rsyslog.conf

$ModLoad imtcp    #取消注释

$InputTCPServerRun 514    #取消注释

添加一下行

local2.*                                                /var/log/haproxy.log

[root@90sec ~]# service rsyslog restart

Shutting down system logger:                               [  OK  ]

Starting system logger:                                    [  OK  ]


2、安装keepalived

[root@90sec src]# tar xf keepalived-1.2.12.tar.gz 

[root@90sec src]# cd keepalived-1.2.12

[root@90sec keepalived-1.2.12]# ./configure --prefix=/usr/local/keepalived --with-dir=/usr/src/kernels/*/

[root@90sec keepalived-1.2.12]# make && make install

[root@90sec keepalived-1.2.12]# mkdir /etc/keepalived

[root@90sec keepalived-1.2.12]# cp -f keepalived/etc/keepalived/keepalived.conf  /etc/keepalived/

[root@90sec keepalived-1.2.12]# cp -f keepalived/etc/init.d/keepalived.init  /etc/init.d/keepalived

[root@90sec keepalived-1.2.12]# cp -f keepalived/etc/init.d/keepalived.sysconfig /etc/sysconfig/keepalived

[root@90sec keepalived-1.2.12]# cp -f /usr/local/keepalived/sbin/keepalived /sbin/

[root@90sec keepalived-1.2.12]# vim /etc/keepalived/keepalived.conf

! Configuration File for keepalived


global_defs {

   notification_email {

        8888@126.com          ##邮件通知

   }

   notification_email_from root@localhost

   smtp_server 127.0.0.1       ##使用本机邮件服务

   smtp_connect_timeout 30

   router_id LVS_DEVEL

}

vrrp_scrip chk_haproxy {        ##判断haproxy服务状态

   script "killall -0 haproxy"

   interval 1

   weight 2

}

vrrp_instance VI_1 {

    state MASTER          #在A 上是主 ,在B 上是备

    interface eth0

    virtual_router_id 200   # 路由ID

    priority 100             #优先级

    advert_int 1

    authentication {         #路由之间认证方式

        auth_type PASS

        auth_pass 1111

    }

    virtual_ipaddress {

        192.168.83.100/24 dev eth0 label eth0:0   #VIP

    }

track_scripts {         #追踪脚本

    chk_haproxy

}

track_interface {        #追踪端口

    eht0

}

notify_master "/etc/keepalived/notify.sh master"       #通知脚本

notify_backup "/etc/keepalived/notify.sh backup"

notify_fault "/etc/keepalived/notify.sh fault"

}


vrrp_instance VI_2 {

    state BACKUP       #在A 上面是备,在B 上是主

    interface eth0

    virtual_router_id 51

    priority 90

    advert_int 1

authentication {

    auth_type PASS

    auth_pass 1111

}

virtual_ipaddress {

         192.168.83.200/24 dev eth0 label eth0:1

}

track_scripts {

     chk_haproxy

}

track_interface {

     eth0

}

}

为keepalived提供脚本服务

#!/bin/bash

#Author: MageEdu <linuxedu@foxmail.com>    #脚本出处

#description: An ample of notify script

vip=192.168.83.100      

contact=‘root@localhost‘

notify() {

mailsubject="`hostname` to be $1: $vip floating"

mailbody="`date ‘+%F %H:%M:%S‘`: vrrp transition, `hostname` changed to be $1"

echo$mailbody | mail -s "$mailsubject"$contact

}

case"$1"in

master)

notify master

/etc/rc.d/init.d/haproxystart

exit0

;;

backup)

notify backup

/etc/rc.d/init.d/haproxystop

exit0

;;

fault)

notify fault

/etc/rc.d/init.d/haproxystop

exit0

;;

*)

echo‘Usage: `basename $0` {master|backup|fault}‘

exit1

;;

esac

配置haproxy B

因为haproxy A 和haproxy B 配置文件相同,所以发送一份即可

[root@90sec /]#scp /etc/haproxy/haproxy.cfg 192.168.83.133:/etc/haproxy/haproxy.cfg

配置heepalived

! Configuration File for keepalived


global_defs {

   notification_email {

        8888@126.com

   }

   notification_email_from root@localhost

   smtp_server 127.0.0.1

   smtp_connect_timeout 30

   router_id LVS_DEVEL

}

vrrp_scrip chk_haproxy {

   script "killall -0 haproxy"

   interval 1

   weight 2

}

vrrp_instance VI_1 {

    state BACKUP

    interface eth0

    virtual_router_id 200

    priority 90

    advert_int 1

    authentication {

        auth_type PASS

        auth_pass 1111

    }

    virtual_ipaddress {

        192.168.83.100 dev eth0 label eth0:0

    }

track_scripts {

    chk_haproxy

}

track_interface {

    eht0

}

}


vrrp_instance VI_2 {

    state MASTER

    interface eth0

    virtual_router_id 51

    priority 100

    advert_int 1

authentication {

    auth_type PASS

    auth_pass 1111

}

virtual_ipaddress {

         192.168.83.200/24 dev eth0 label eth0:1

}

track_scripts {

     chk_haproxy

}

track_interface {

     eht0

}

notify_master "/etc/keepalived/notify.sh master"

notify_backup "/etc/keepalived/notify.sh backup"

notify_fault "/etc/keepalived/notify.sh fault"

}

注意:

notify_master "/etc/keepalived/notify.sh master"
notify_backup "/etc/keepalived/notify.sh backup"

notify_fault "/etc/keepalived/notify.sh fault"


3个状态分别要执行的脚本,只能放在 MASTER中,原因是:因为是互为主从,每个主的都会有个另外一个主的从,如果

把这 “3个状态执行脚本” 写入到从的区域中,那么另外一个主的从状态就会执行这个脚本,因为就会停掉所要高可用的

程序,这就造成了,两个VIP全部转移到其中一个服务器上去。

keepalived提供脚本服务相同,所以只需修改VIP 地址即可。日志配置方式也相同,参照上面即可。

四、测试keeplived功能

二个节点服务正常时

wKiom1QkHY-QQbeJAAMCKApywgA324.jpg

wKiom1QkHa7BgtqsAAK1NI_ktDk555.jpg

关闭haproxy A 上的keepalived看VIP 是否漂移

wKioL1QkHenx5386AALjHq6VbCo749.jpg

wKiom1QkHcyiTOfuAANoYvHaQEA793.jpg




五、配置后端web服务

为web1 静态配置,并上传一张图片

wKioL1QkE-6wxE3vAAEvwbnEBAw303.jpg


为web2动态配置


# yum install -y php php-mysql

# vim /var/www/html/index.php

<h1>WebCome to WEB2</h1>

<?php

phpinfo();

?>

# service httpd start

Starting httpd:                                           [  OK  ]






























本文出自 “断了的军刀” 博客,请务必保留此出处http://90sec.blog.51cto.com/7404127/1558170

keepalived + haproxy 实现web的高可用负载均衡