HAProxy 高级应用

================================================================================

概述:

 本章将继续介绍haproxy的一些其他应用,具体内容如下:

  • use_backend <backend> 后端主机调用:

  • haproxy中tcp模式的应用;

  • haproxy中listen的应用

================================================================================

7层检查机制:path、req.hdr、res.hdr

path : string

  • This extracts the request's URL path, which starts at the first slash and ends before the question mark (without the host part).  //提取用户请求的URL路径与对应的请求报文的url作比较,从第一个斜杠开始和到问号之前的内容(没有主机部分)。

ACL derivatives :

  • path     : exact string match(字符窜精确匹配)

  • path_beg : prefix match(前缀匹配)

  • path_dir : subdir match(子目录匹配)

  • path_dom : domain match(域匹配)

  • path_end : suffix match(后缀匹配)

  • path_len : length match(长度匹配)

  • path_reg : regex match(正则匹配)

  • path_sub : substring match(子串匹配)

演示:

 1.拒绝用户访问以.txt结尾的资源,编辑配置文件如下:

wKiom1gz1ADRc-66AABXublu30I521.png

 

 重载haproxy服务,向RS1提供一个.txt结尾的文件

[root@RS1 ~]# cp /etc/fstab /var/www/html/fstab.txt

 在浏览器中请求此资源,发现拒绝访问,说明我们在配置文件中定义的path生效了,如下:

wKiom1gz1UHQSIkcAABNeGZks4U745.png

req.hdr([<name>[,<occ>]]) : string 

  • 对请求报文中的内容做检查

  • This extracts the last occurrence of header <name> in an HTTP request.

ACL derivatives :

  • hdr([<name>[,<occ>]])          : exact string match

  • hdr_beg([<name>[,<occ>]])  : prefix match

  • hdr_dir([<name>[,<occ>]])    : subdir match

  • hdr_dom([<name>[,<occ>]]) : domain match

  • hdr_end([<name>[,<occ>]])  : suffix match

  • hdr_len([<name>[,<occ>]])   : length match

  • hdr_reg([<name>[,<occ>]])   : regex match

  • hdr_sub([<name>[,<occ>]])  : substring match

res.hdr([<name>[,<occ>]]) : string

  • 对响应报文中的内容做检测

ACL derivatives :

  • shdr([<name>[,<occ>]])          : exact string match

  • shdr_beg([<name>[,<occ>]])  : prefix match

  • shdr_dir([<name>[,<occ>]])    : subdir match

  • shdr_dom([<name>[,<occ>]]) : domain match

  • shdr_end([<name>[,<occ>]])   : suffix match

  • shdr_len([<name>[,<occ>]])   : length match

  • shdr_reg([<name>[,<occ>]])   : regex match

  • shdr_sub([<name>[,<occ>]])   : substring match


演示:

 1.禁止使用Firefox浏览器访问内容,编辑配置文件,如下:

wKiom1gz8gmwY7SqAABfY0TZbnk450.png

 

  重载haproxy服务,使用Firefox浏览器访问可以发现403拒绝访问,使用chrome和其他浏览器可以正常访问,如下:

wKioL1gz8xqB6kJzAABJjA9Jsu4096.png

url : string

  • This extracts the request's URL as presented in the request.

ACL derivatives :

  • url           : exact string match

  • url_beg   : prefix match

  • url_dir     : subdir match

  • url_dom  : domain match

  • url_end   : suffix match

  • url_len     : length match

  • url_reg    : regex match

  • url_sub   : substring match

method : integer + string

  • 检查请求报文中的请求方法

Example :

# only accept GET and HEAD requests
acl valid_method method GET HEAD
http-request deny if ! valid_method

注意:

  • HAProxy有众多内建的ACLs,这些ACLs可直接调用,例如LOCALHOST,TRUE,HTTP;

wKiom1gz_d-RPnT7AACAe00T2y4205.png

wKioL1gz_eCAQSKtAABT9EhRIrE355.png


 13.访问控制相关的参数:

http层的访问控制参数

block { if | unless } <condition>

  • 作用:阻止符合指定acl的访问请求; 

  • 范围:frontend、listen、backend

Example:

acl invalid_src  src          0.0.0.0/7 224.0.0.0/3
acl invalid_src  src_port     0:1023
acl local_dst    hdr(host) -i localhost
block if invalid_src || local_dst

http-request { allow | deny} [ { if | unless } <condition> ]

   ---Access control for Layer 7 requests(7层访问控制)

Example:

acl nagios src 192.168.129.3
acl local_net src 192.168.0.0/16
acl auth_ok http_auth(L1)

http-request allow if nagios
http-request allow if local_net auth_ok
http-request auth realm Gimme if local_net auth_ok
http-request deny

演示:

  1.仅允许本地主机访问admin目录,编辑配置文件,如下:

wKioL1g0BD6hLwdUAABQgbHxc4E924.png


 在后端主机创建对应的admin目录,并提供其测试页面,如下:

[root@RS1 ~]# mkdir /var/www/html/admin
[root@RS1 ~]# echo "<h1>Admin</h1>" > /var/www/html/admin/index.html
[root@RS1 ~]# cat /var/www/html/admin/index.html
<h1>Admin</h1>

 在浏览器中访问(10.1.250.25)提示403没有访问权限,在本机使用curl可以正常访问,如下:

wKioL1g0BNyCvMrnAABHRXdoLNo025.png

[root@centos7 haproxy]# curl http://10.1.252.153/admin/
<h1>Admin</h1>

--------------------------------------------------------------------------------

TCP层的访问控制参数

tcp-request connection <action> [{if | unless} <condition>]

  • ---Perform an action on an incoming connection depending on a layer condition

tcp-request content <action> [{if | unless} <condition>]

  • ---Perform an action on a new session depending on a layer 4-7 condition

wKiom1g0CuaTyUexAAA58xMsXKk865.png

Example:

tcp-request connection accept if { src -f /etc/haproxy/whitelist.lst }
tcp-request connection track-sc0 src
tcp-request connection reject if { sc0_conn_rate gt 10 }

Example:

# Accept HTTP requests containing a Host header saying "example.com"
# and reject everything else.acl is_host_com hdr(Host) -i example.com
tcp-request inspect-delay 30s
tcp-request content accept if is_host_com
tcp-request content reject

 13.后端主机调用:

use_backend <backend> [{if | unless} <condition>]

  • ---Switch to a specific backend if/unless an ACL-based condition is matched.(满足acl条件时就调度到指定的后端主机

示例:

 使用use_backend实现动静分离

wKioL1g0Jinx9Zs2AABg-7JkZi0296.png




HAProxy的tcp模式应用

实验:使用haproxy调度后端主机的SSH服务

实验环境描述:

  • 三台虚拟主机,一台作为haproxy的调度器,另外两台作为后端的原始web服务器;

  • haproxy调度器有两块网卡,一块作为外网网卡,负责接收用户的请求,一块为内网网卡,负责与内网的后端原始web服务器通信;(要打开核心件转发功能)

IP地址规划:

  • 两台后端主机使用内网地址RS1(192.168.111.128);RS2(192.168.111.129),与haproxy的内网网卡基于VMnet1通信;

  • haprosy外网地址ip(10.1.252.153);内网地址ip(192.168.111.130)

实验过程如下:

------------------------------------------------------------------------------------------------------

 1.编辑haproxy的配置文件,定义前端frontend和后端backend具体如下:

 frontend ssh
      bind *:22022            //为了和本机区分使用22022
      mode  tcp               
      default_backend sshsrvs 
  
 backend sshsrvs
      balance leastconn      //使用最少连接算法
      server  ssh1 192.168.111.128:22 check  
      server  ssh2 192.168.111.129:22 check

 2.重载haproxy服务,然后登录SSH服务,可以发现可以正常连接到后端的两台原始服务器,如下:

[root@centos7 haproxy]# ssh -p 22022 10.1.252.153
The authenticity of host '[10.1.252.153]:22022 ([10.1.252.153]:22022)' can't be established.
ECDSA key fingerprint is cb:36:da:6b:15:d6:60:25:a7:28:f1:bf:b3:22:ce:c0.
Are you sure you want to continue connecting (yes/no)? yes
[root@centos7 ~]# ifconfig
eno16777736: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.111.129  netmask 255.255.255.0  broadcast 192.168.111.255
        inet6 fe80::20c:29ff:feca:6ef1  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:ca:6e:f1  txqueuelen 1000  (Ethernet)
        RX packets 156021  bytes 13141000 (12.5 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 24359  bytes 1858526 (1.7 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 0  (Local Loopback)
        RX packets 32  bytes 2720 (2.6 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 32  bytes 2720 (2.6 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

[root@centos7 ~]# exit
logout
Connection to 10.1.252.153 closed.

[root@centos7 haproxy]# ssh -p 22022 10.1.252.153   
The authenticity of host '[10.1.252.153]:22022 ([10.1.252.153]:22022)' can't be established.
ECDSA key fingerprint is 56:78:d2:e8:41:b0:62:ad:4f:47:90:75:01:a4:fa:8c.
Are you sure you want to continue connecting (yes/no)? yes
[root@centos7 ~]# ifconfig
eno16777736: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.111.128  netmask 255.255.255.0  broadcast 192.168.111.255
        inet6 fe80::20c:29ff:fed6:e460  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:d6:e4:60  txqueuelen 1000  (Ethernet)
        RX packets 157051  bytes 13309701 (12.6 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 25174  bytes 1963784 (1.8 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 0  (Local Loopback)
        RX packets 59  bytes 4880 (4.7 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 59  bytes 4880 (4.7 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0




HAProxy中listen的应用

1.如上例,我们也可以使用listen将两个单独的forontend和backend整合到一起,如下:

  listen ssh  
      bind *:22022
      mode  tcp
      balance leastconn
      server  ssh1 192.168.111.128:22 check
      server  ssh2 192.168.111.129:22 check

 2.我们也可以将stats统计信息状态页使用listen整合到一起,如下:

   listen stats
        bind *:9527
        stats enable
        stats uri /admin?stats
        stats realm Stats\ Page\ Area
        stats auth taotao:xiuxiu 
        stats refresh 5s
        stats hide-version

 3.重载haproxy服务,查看监听的端口9527,如下:

 [root@centos7 haproxy]# systemctl reload haproxy.service 
 [root@centos7 haproxy]# ss -tnl
State       Recv-Q Send-Q                                      Local Address:Port                 
LISTEN      0      128                                             127.0.0.1:6012                 
LISTEN      0      25                                                      *:514                  
LISTEN      0      128                                                     *:22022                
LISTEN      0      128                                                     *:8080                 
LISTEN      0      128                                                     *:80                   
LISTEN      0      128                                                     *:22                   
LISTEN      0      128                                                     *:9527

 4.在浏览器中访问stats统计页状态信息如下:

wKioL1g0Nn3x3-GfAAGH3erfjIc176.png

wKiom1g0Nn6CmEPXAACV3dAsRsE767.png




http服务器配置案例:

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    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

defaults
    mode                    http
    log                     global
    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                 30000

listen stats
    mode http
    bind 0.0.0.0:1080
    stats enable
    stats hide-version
    stats uri     /haproxyadmin?stats
    stats realm   Haproxy\ Statistics
    stats auth    admin:admin
    stats admin if TRUE


frontend http-in
    bind *:80
    mode http
    log global
    option httpclose
    option logasap
    option dontlognull
    capture request  header Host len 20
    capture request  header Referer len 60
    default_backend servers

frontend healthcheck
    bind :1099
    mode http
    option httpclose
    option forwardfor
    default_backend servers

backend servers
  balance roundrobin
    server websrv1 192.168.10.11:80 check maxconn 2000
    server websrv2 192.168.10.12:80 check maxconn 2000

负载均衡MySQL服务的配置示例

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    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

defaults
    mode                    tcp
    log                     global
    option                  httplog
    option                  dontlognull
    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                 600

listen stats
    mode http
    bind 0.0.0.0:1080
    stats enable
    stats hide-version
    stats uri     /haproxyadmin?stats
    stats realm   Haproxy\ Statistics
    stats auth    admin:admin
    stats admin if TRUE


frontend mysql
    bind *:3306
    mode tcp
    log global
    default_backend mysqlservers

backend mysqlservers
    balance leastconn
    server dbsrv1 192.168.10.11:3306 check port 3306 intval 2 rise 1 fall 2 maxconn 300
    server dbsrv2 192.168.10.12:3306 check port 3306 intval 2 rise 1 fall 2 maxconn 300

动静分离案例:

global
    log         127.0.0.1 local2

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

defaults
    mode                    http
    log                     global
    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                 30000

listen stats
    mode http
    bind 0.0.0.0:1080
    stats enable
    stats hide-version
    stats uri     /haproxyadmin?stats
    stats realm   Haproxy\ Statistics
    stats auth    admin:admin
    stats admin if TRUE


frontend http-in
    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 /p_w_picpaths /javascript /stylesheets
    acl url_static       path_end       -i .jpg .jpeg .gif .png .css .js

    use_backend static_servers          if url_static
    default_backend dynamic_servers

backend static_servers
    balance roundrobin
    server imgsrv1 172.16.200.7:80 check maxconn 6000
    server imgsrv2 172.16.200.8:80 check maxconn 6000

backend dynamic_servers
	cookie srv insert nocache
    balance roundrobin
    server websrv1 172.16.200.7:80 check maxconn 1000 cookie websrv1
    server websrv2 172.16.200.8:80 check maxconn 1000 cookie websrv2
    server websrv3 172.16.200.9:80 check maxconn 1000 cookie websrv3