设为首页 收藏本站
查看: 916|回复: 0

[经验分享] HAProxy 高级应用(二)

[复制链接]

尚未签到

发表于 2019-1-1 11:06:43 | 显示全部楼层 |阅读模式
HAProxy 高级应用

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

  •   use_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结尾的资源,编辑配置文件如下:


重载haproxy服务,向RS1提供一个.txt结尾的文件
[root@RS1 ~]# cp /etc/fstab /var/www/html/fstab.txt 在浏览器中请求此资源,发现拒绝访问,说明我们在配置文件中定义的path生效了,如下:

req.hdr([[,]]) : string

  • 对请求报文中的内容做检查
  • This extracts the last occurrence of header  in an HTTP request.
ACL derivatives :

  • hdr([[,]])          : exact string match
  • hdr_beg([[,]])  : prefix match
  • hdr_dir([[,]])    : subdir match
  • hdr_dom([[,]]) : domain match
  • hdr_end([[,]])  : suffix match
  • hdr_len([[,]])   : length match
  • hdr_reg([[,]])   : regex match
  • hdr_sub([[,]])  : substring match
res.hdr([[,]]) : string

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

  • shdr([[,]])          : exact string match
  • shdr_beg([[,]])  : prefix match
  • shdr_dir([[,]])    : subdir match
  • shdr_dom([[,]]) : domain match
  • shdr_end([[,]])   : suffix match
  • shdr_len([[,]])   : length match
  • shdr_reg([[,]])   : regex match
  • shdr_sub([[,]])   : substring match


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


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

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;




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


http层的访问控制参数
block { if | unless }

  • 作用:阻止符合指定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_dsthttp-request { allow | deny} [ { if | unless }  ]
  ---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目录,编辑配置文件,如下:



在后端主机创建对应的admin目录,并提供其测试页面,如下:
[root@RS1 ~]# mkdir /var/www/html/admin
[root@RS1 ~]# echo "Admin" > /var/www/html/admin/index.html
[root@RS1 ~]# cat /var/www/html/admin/index.html
Admin 在浏览器中访问(10.1.250.25)提示403没有访问权限,在本机使用curl可以正常访问,如下:

[root@centos7 haproxy]# curl http://10.1.252.153/admin/
Admin--------------------------------------------------------------------------------

TCP层的访问控制参数
tcp-request connection  [{if | unless} ]

  • ---Perform an action on an incoming connection depending on a layer 4 condition
tcp-request content  [{if | unless} ]

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

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  [{if | unless} ]

  • ---Switch to a specific backend if/unless an ACL-based condition is matched.(满足acl条件时就调度到指定的后端主机)
  示例:
   使用use_backend实现动静分离
  

  

  
  
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  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
        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  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10
        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  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
        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  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10
        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统计页状态信息如下:
  


  

  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 /images /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  

  

  

  

  





运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-658207-1-1.html 上篇帖子: HAproxy(二)动静分离 下篇帖子: HAProxy 基础入门
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表