基于haproxy的负载均衡和访问控制

HAProxy是一个使用C语言编写的自由及开放源代码软件,其提供高可用性、负载均衡,以及基于TCP和HTTP的应用程序代理。HAProxy特别适用于那些负载特大的web站点,这些站点通常又需要会话保持或七层处理。HAProxy运行在当前的硬件上,完全可以支持数以万计的并发连接。并且它的运行模式使得它可以很简单安全的整合进您当前的架构中,同时可以保护你的web服务器不被暴露到网络上。


 Haproxy八种负载均衡算法(balance)

1.balance roundrobin          ###轮询,软负载均衡基本都具备这种算法
2.balance static-rr           ###根据权重
3.balance leastconn           ###最少连接数先处理
4.balance source              ###分局请求的IP
5.balance uri                 ###分局请求的uri
6.balance url_param           ###根据请求的URL参数
7.banlance hdr(name)          ###根据HTTP请求头来锁定每一次HTTP请求
8.balance rbp-cookie(name)    ###根据cookie来锁定hash每一次TCP请求

Haproxy的安装过程

(1)构建RPM包并安装

tar zxf haproxy-1.6.11.tar.gz     #解压tar包
yum install rpm-build -y           #安装rpm包制作工具
rpmbuild -tb haproxy-1.6.11.tar.gz    #将其制作为rpm包
cd rpmbuild/RPMS/
cd x86_64/
rpm -qpl haproxy-1.6.11-1.x86_64.rpm  (查看下载后得到的相关文件)
rpm -ivh haproxy-1.6.11-1.x86_64.rpm (安装)

 

cd haproxy-1.6.11/examples
cp content-sw-sample.cfg /etc/haproxy/haproxy.cfg    将模板中的配置文件移到对应目录下

 

(2)添加haproxy用户和组

grep 200 /etc/passwd
groupadd -g 200 haproxy    建立一个haproxy组
useradd -u 200 -g 200 -M haproxy
id haproxy

haproxy配置负载均衡

(1)修改配置

#
# This is a sample configuration. It illustrates how to separate static objects
# traffic from dynamic traffic, and how to dynamically regulate the server load.
#
# It listens on 192.168.1.10:80, and directs all requests for Host 'img' or
# URIs starting with /img or /css to a dedicated group of servers. URIs
# starting with /admin/stats deliver the stats page.
#

global
        maxconn         10000
        stats socket    /var/run/haproxy.stat mode 600 level admin
        log             127.0.0.1 local0
        uid             200
        gid             200
        chroot          /var/empty
        daemon

# The public 'www' address in the DMZ
frontend public
        bind            *:80 name clear
        #bind            192.168.1.10:443 ssl crt /etc/haproxy/haproxy.pem
        mode            http
        log             global
        option          httplog
        option          dontlognull
        monitor-uri     /monitoruri
        maxconn         8000
        timeout client  30s

        stats uri       /admin/stats
        #use_backend     static if { hdr_beg(host) -i img }
        #use_backend     static if { path_beg /img /css   }
        default_backend static  #默认将访问发送到static的后端服务器群

# The static backend backend for 'Host: img', /img and /css.
backend static
        mode            http
        balance         roundrobin
        option prefer-last-server
        retries         2
        option redispatch
        timeout connect 5s
        timeout server  5s
        #option httpchk  HEAD /favicon.ico
        server          statsrv1 172.25.1.2:80 check inter 1000  #定义后端的服务器
        server          statsrv2 172.25.1.3:80 check inter 1000

# the application servers go here
backend dynamic
        mode            http
        balance         roundrobin
        retries         2
        option redispatch
        timeout connect 5s
        timeout server  30s
        timeout queue   30s
        option httpchk  HEAD /login.php
        cookie          DYNSRV insert indirect nocache
        fullconn        4000 # the servers will be used at full load above this number of connections
        server          dynsrv1 192.168.1.1:80 minconn 50 maxconn 500 cookie s1 check inter 1000
        server          dynsrv2 192.168.1.2:80 minconn 50 maxconn 500 cookie s2 check inter 1000
        server          dynsrv3 192.168.1.3:80 minconn 50 maxconn 500 cookie s3 check inter 1000
        server          dynsrv4 192.168.1.4:80 minconn 50 maxconn 500 cookie s4 check inter 1000

(2)启动服务

[root@server1 ~]# /etc/init.d/haproxy start

(3)测试haproxy负载均衡:

在server2和server3中安装httpd,对默认发布目录进行设置

访问172.25.12.1,server2和server3中的内容会进行轮询

 

haproxy配置访问网站为动静分离

(1)配置:(部分配置)

frontend public
        bind            *:80 name clear
        #bind            192.168.1.10:443 ssl crt /etc/haproxy/haproxy.pem

        #use_backend     static if { hdr_beg(host) -i img }
        #use_backend     static if { path_beg /img /css   }     
        use_backend     static2 if { path_end -i .php   }  # 访问路径中为.php结尾的页面时候去访问static2
        default_backend static1   # 静态页面,采用默认访问路径

# The static backend backend for 'Host: img', /img and /css.
backend static1
        balance         roundrobin
        server          statsrv1 172.25.12.2:80 check inter 1000
backend static2
        balance         roundrobin
        server          statsrv2 172.25.12.3:80 check inter 1000

(2)server3中安装php

[root@server3 ~]# yum install -y php
[root@server3 ~]# vim /var/www/html/index.php 
<?php
phpinfo()
?>
[root@server3 ~]# /etc/init.d/httpd start

测试 :

当访问172.25.1.1时候会去主动访问server2

访问172.25.1.1/index.php的时候会去访问server3中的php文件

 

修改haproxy的日志路径

(1)配置文件中查看haproxy的日志设备

global
        maxconn         10000
        stats socket    /var/run/haproxy.stat mode 600 level admin
        log             127.0.0.1 local0   #日志设备为local0
        uid             200
        gid             200
        chroot          /var/empty
        daemon

(2) 修改日志文件


vim /etc/rsyslog.conf

 13 $ModLoad imudp          #注释去掉
 14 $UDPServerRun 514      #注释去掉

*.info;mail.none;authpriv.none;cron.none;local0.none   # /var/log/messages #添加local0:none

# The authpriv file has restricted access.
authpriv.*                                              /var/log/secure

# Log all the mail messages in one place.
mail.*                                                  -/var/log/maillog


# Log cron stuff
cron.*                                                  /var/log/cron

# Everybody gets emergency messages
*.emerg                                                 *

# Save news errors of level crit and higher in a special file.
uucp,news.crit                                          /var/log/spooler

# Save boot messages also to boot.log
local7.*                                                /var/log/boot.log
local0.*                                                /var/log/haporxy.log  
######### local0的日志放在/var/log/haporxy.log

(3)重新启动 /etc/init.d/rsyslog restart

[root@server1 ~]# cd /var/log/
[root@server1 log]# ls
audit     cron   dmesg.old  httpd    messages  secure   wtmp
boot.log  dmesg  haproxy.log    maillog  rhsm      spooler  yum.log

haproxy的访问控制

(1)将特定用户进行拒绝,或重新定向

 34 frontend public
 35         bind            *:80 name clear
 36         #bind            192.168.1.10:443 ssl crt /etc/haproxy/haproxy.pem
 37
 38         #use_backend     static if { hdr_beg(host) -i img }
 39         #use_backend     static if { path_beg /img /css   }
 40         acl blacklist src 172.25.1.250    #创建访问黑名单,blacklist为自己定义的名字
 43         http-request deny if blacklist     #对blacklist里面的用户进行拒绝
 44         #errorloc 403 http://172.25.1.1:8080   
#可以将访问拒绝的403信息重定向到172.25.1.1上的8080端口
 48         default_backend static1

44行代表把黑名单中的用户拒绝以后,然后将用户的请求403错误重新定向到一个新的目的网址,可以利用新的目的网址去发布错误信息或维护通知,也可以对用户直接进行拒绝

(2)将所有的用户进行重新定向

frontend public
        bind            *:80 name clear
        #bind            192.168.1.10:443 ssl crt /etc/haproxy/haproxy.pem

        #use_backend     static if { hdr_beg(host) -i img }
        #use_backend     static if { path_beg /img /css   }
        redirect location http://www.baidu.com   #将所有的用户访问定向到www.baidu.com
        default_backend static1

设置以后那么所有的用户访问static1都会被重新定向到www.baidu.com

(3)将指定用户进行重新定向

frontend public
        bind            *:80 name clear
        #bind            192.168.1.10:443 ssl crt /etc/haproxy/haproxy.pem

        #use_backend     static if { hdr_beg(host) -i img }
        #use_backend     static if { path_beg /img /css   }
        acl redhat src 172.25.1.250  #定义此用户为redhat
        redirect location http://172.25.1.1:8080 if redhat  #如果是redhat的用户,则进行重定向

        default_backend static1

haproxy进行读写分离

配置信息

frontend public
        bind            *:80 name clear
        #bind            192.168.1.10:443 ssl crt /etc/haproxy/haproxy.pem

        #use_backend     static if { hdr_beg(host) -i img }
        #use_backend     static if { path_beg /img /css   }
        acl write method POST    #写的动作
        acl write method PUT 
        #use_backend     static2 if { path_end -i .php   }
        use_backend     static2 if write    #如果是write的动作那么在static2上进行
        default_backend static1       #默认会去访问static1
backend static1
        balance         roundrobin
        server          statsrv1 172.25.1.2:80 check inter 1000
backend static2
        balance         roundrobin
        server          statsrv2 172.25.1.3:80 check inter 1000

在默认情况下,访问页面是访问的static1中的数据,但是在写的情况下,会将数据存入到static2中,从而实现读写分离

在server3和server2中的httpd默认发布目录,放进去index.php(选择图片的静态页面)和upload_file.php(上传图片的动态页面),在默认发布目录创建存放上传图片upload目录,修改权限为777。

index.php:
<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

 

upload_file.php:
<?php
if ((($_FILES["file"]["type"] == "image/gif")  
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))  # 图片的三种格式(只能上传着三种)
&& ($_FILES["file"]["size"] < 2000000))   # 上传图片的大小(k为单位),可以自己调节大小
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {    # 上传成功显示的信息(所以上传图片是个动态的过程)
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";  # 不符合上传条件显示Invalid file
  }
?>

测试:

 

 

 

图片存储到了server3中

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值