四层与七层的区别:
• 四层:
• 在四层负载设备中,把client发送的报文目标地址(原来是负载均衡设备的IP地址),根
据均衡设备设置的选择web服务器的规则选择对应的web服务器IP地址,这样client就
可以直接跟此服务器建立TCP连接并发送数据。
• 七层:
• 七层负载均衡服务器起了一个代理服务器的作用,服务器建立一次TCP连接要三次握手,而
client要访问webserver要先与七层负载设备进行三次握手后建立TCP连接,把要访问的报文信息
发送给七层负载均衡;然后七层负载均衡再根据设置的均衡规则选择特定的webserver,然后通
过三次握手与此台webserver建立TCP连接,然后webserver把需要的数据发送给七层负载均衡设
备,负载均衡设备再把数据发送给client;所以,七层负载均衡设备起到了代理服务器的作用。
七层IP 透传:
• 七层负载:
• listen web_prot_http_nodes
• bind 192.168.7.102:80
• mode http
• #option forwardfor
server 192.168.7.102 blogs.studylinux.net:80 check inter 3000 fall 3 rise 5
四层IP 透传:
• 四层负载:
• listen web_prot_http_nodes
• bind 192.168.7.102:80
• mode tcp
• server 192.168.7.102 blogs.studylinux.net:80 send-proxy check inter 3000 fall 3 rise 5
• Nginx配置:
• listen 80 proxy_protocol;
• '"tcp_ip":"$proxy_protocol_addr",' #TCP获取客户端真实IP日志格式
Cookie 配置
• cookie <value>:为当前server指定cookie值,实现基于cookie的会话黏性
cookie <name> [ rewrite | insert | prefix ] [ indirect ] [ nocache ] [ postonly ] [
preserve ] [ httponly ] [ secure ] [ domain <domain> ]* [ maxidle <idle> ] [
maxlife <life> ]
<name>:cookie名称,用于实现持久连接
rewrite:重写
insert:插入
prefix:前缀
nocache:当client和hapoxy之间有缓存时,不缓存cookie
Cookie配置实例
• 基于cookie实现的session 保持
listen web_prot_http_nodes
bind 192.168.7.102:80
mode http
cookie SERVER-COOKIE insert indirect nocache
server 192.168.7.101 192.168.7.101:8080 cookie web1 check inter 3000 fall 3 rise 5
server 192.168.7.102 192.168.7.102:8080 cookie web2 check inter 3000 fall 3 rise 5
配置HAProxy状态页:
pid = 3698 (process #2, nbproc = 2, nbthread = 2) #pid为当前pid号,process为当前进程号,nbproc和nbthread为一共多
少进程和每个进程多少个线程
uptime = 0d 0h00m08s #启动了多长时间
system limits: memmax = unlimited; ulimit-n = 131124 #系统资源限制:内存/最大打开文件数/
maxsock = 131124; maxconn = 65536; maxpipes = 0 #最大socket连接数/单进程最大连接数/最大管道数maxpipes
current conns = 1; current pipes = 0/0; conn rate = 1/sec #当前连接数/当前管道数/当前连接速率
Running tasks: 1/9; idle = 100 % #运行的任务/当前空闲率
active UP:#在线服务器 backup UP:#标记为backup的服务器
active UP, going down: #监测未通过正在进入down过程 backup UP, going down:#备份服务器正在进入down过程
active DOWN, going up: #down的服务器正在进入up过程 backup DOWN, going up:#备份服务器正在进入up过程
active or backup DOWN: #在线的服务器或者是backup的服务器已经转换成了down状态 not checked:#标记为不监
测的服务器
active or backup DOWN for maintenance (MAINT) #active或者backup服务器认为下线的
active or backup SOFT STOPPED for maintenance #active或者backup被认为软下线(人为将weight改成0)
修改报文首部
• 在请求报文尾部添加指定报文:
reqadd <string> [{if | unless} <cond>] #支持条件判断
• 在响应报文尾部添加指定报文:
rspadd <string> [{if | unless} <cond>]
示例:rspadd X-Via:\ HAPorxy
• 从请求报文中删除匹配正则表达式的首部
reqdel <search> [{if | unless} <cond>]
reqidel <search> [{if | unless} <cond>] 不分大小
• 从响应报文中删除匹配正则表达式的首部
rspdel <search> [{if | unless} <cond>]
rspidel <search> [{if | unless} <cond>]
示例: rspidel server.* #从相应报文删除server信息
rspidel X-Powered-By:.* #从响应报文删除X-Powered-By信息
HAProxy 日志配置
• 在default配置项定义:
• log 127.0.0.1 local{1-7} info #基于syslog记录日志到指定设备,级别有(err、warning、info、debug)
• 配置rsyslog:
• $ModLoad imudp
• $UDPServerRun 514
• local3.* /var/log/haproxy.log
• 配置HAProxy:
• listen web_port
• bind 127.0.0.1:80
• mode http
• log global
• option tcplog
• server web1 127.0.0.1:8080 check inter 3000 fall 2 rise 5
• 重启syslog服务并访问haproxy状态页
自定义记录日志
• 将特定信息记录在日志中(1.8版本不生效)
• capture cookie <name> len <length> #捕获请求和响应报文中的 cookie并记录日志
• capture request header <name> len <length> #捕获请求报文中指定的首部内容和长度并记录日志
• capture response header <name> len <length> #捕获响应报文中指定的内容和长度首部并记录日志
• 示例:
• capture request header Host len 256
• capture request header User-Agent len 512
压缩功能
• compression algo #启用http协议中的压缩机制,常用算法有gzip deflate
• compression type #要压缩的类型
• 示例:
• compression algo gzip deflate
• compression type text/plain text/html text/css text/xml text/javascript application/javascript
Web服务器状态监测:
• 三种状态监测方式:
• 基于四层的传输端口做状态监测
• server 172.18.200.103 172.18.200.103:80 check port 9000 addr 172.18.200.104 inter 3s fall 3 rise 5 weight 1
• 基于指定URI 做状态监测
• 基于指定URI的request请求头部内容做状态监测
• option httpchk
• option httpchk <uri>
• option httpchk <method> <uri>
• option httpchk <method> <uri> <version>
• listen web_prot_http_nodes
• bind 192.168.7.102:80
• mode http
• log global
• option httpchk GET /wp-includes/js/jquery/jquery.js?ver=1.12.4 HTTP/1.0 #基于指定URL
• #option httpchk HEAD /wp-includes/js/jquery/jquery.js?ver=1.12.4 HTTP/1.0\r\nHost:\ 192.168.7.102 #通过request获取的头部信息进行匹配进行健康检测
• server 192.168.7.102 blogs.studylinux.net:80 check inter 3000 fall 3 rise 5
• server 192.168.7.101 192.168.7.101:8080 cookie web1 check inter 3000 fall 3 rise 5
ACL
• acl:对接收到的报文进行匹配和过滤,基于请求报文头部中的源地址、源端口、目标地址、目标端口、请求方法、URL、文件后缀等信息内容进行匹配并执行进一步操作。
• acl <aclname> <criterion> [flags] [operator] [<value>]
• acl 名称 条件 条件标记位 具体操作符 操作对象类型
• acl image_service hdr_dom(host) -i img.magedu.com
• ACL名称,可以使用大字母A-Z、小写字母a-z、冒号:、点.、中横线和下划线,并且严格区分大小写,必须Image_site和image_site完全是两个acl。
• ACL derivatives :
• hdr([<name> [,<occ>]]):完全匹配字符串
• hdr_beg([<name> [,<occ>]]):前缀匹配
• hdr_dir([<name> [,<occ>]]):路径匹配
• hdr_dom([<name> [,<occ>]]):域匹配
• hdr_end([<name> [,<occ>]]):后缀匹配
• hdr_len([<name> [,<occ>]]):长度匹配
• hdr_reg([<name> [,<occ>]]):正则表达式匹配
• hdr_sub([<name> [,<occ>]]):子串匹配
Criterion-acl
• <criterion> :匹配条件
• dst 目标IP
• dst_port 目标PORT
• src 源IP
• src_port 源PORT
• hdr <string>用于测试请求头部首部指定内容
• hdr_dom(host) 请求的host名称,如 www.magedu.com
• hdr_beg(host) 请求的host开头,如 www. img. video. download. ftp.
• hdr_end(host) 请求的host结尾,如 .com .net .cn
• path_beg 请求的URL开头,如/static、/images、/img、/css
• path_end 请求的URL中资源的结尾,如 .gif .png .css .js .jpg .jpeg
flags
• <flags>-条件标记
-i 不区分大小写
-m 使用指定的pattern匹配方法
-n 不做DNS解析
-u 禁止acl重名,否则多个同名ACL匹配或关系
operator
• [operator]-操作符:
• 整数比较:eq、ge、gt、le、lt
字符比较:
- exact match (-m str) :字符串必须完全匹配模式
- substring match (-m sub) :在提取的字符串中查找模式,如果其中任何一个被发现,ACL将匹配
- prefix match (-m beg) :在提取的字符串首部中查找模式,如果其中任何一个被发现,ACL将匹配
- suffix match (-m end) :将模式与提取字符串的尾部进行比较,如果其中任何一个匹配,则ACL进行匹配
- subdir match (-m dir) :查看提取出来的用斜线分隔(“/”)的字符串,如果其中任何一个匹配,则ACL进行匹配
- domain match (-m dom) :查找提取的用点(“.”)分隔字符串,如果其中任何一个匹配,则ACL进行匹配
value
• <value>的类型:
- Boolean #布尔值false,true
- integer or integer range #整数或整数范围,比如用于匹配端口范围,1024~32768
- IP address / network #IP地址或IP范围, 192.168.0.1 ,192.168.0.1/24
- string
exact –精确比较 www.magedu.com
substring—子串 www.magedu.com
suffix-后缀比较 www.magedu.com
prefix-前缀比较 www.magedu.com
subdir-路径, /wp-includes/js/jquery/jquery.js
domain-域名,www.magedu.com
- regular expression #正则表达式
- hex block #16进制
Acl定义与调用
• 多个acl作为条件时的逻辑关系:
- 与:隐式(默认)使用
- 或:使用“or” 或 “||”表示
- 否定:使用“!“ 表示
示例:
if valid_src valid_port #与关系
if invalid_src || invalid_port #或
! invalid_src #非
Acl 示例-域名匹配:
• listen web_port
• bind 192.168.7.102:8800
• mode http
• log global
• acl test_host hdr_dom(host) www.magedu.com
• use_backend test_host if test_host
• default_backend default_web #以上都没有匹配到的时候使用默认backend
• backend test_host
• mode http
• server web1 www.magedu.com check inter 2000 fall 3 rise 5
• backend default_web
• mode http
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
Acl-源地址子网匹配
• listen web_port
• bind 192.168.7.102:8800
• mode http
• log global
• acl ip_range_test src 172.18.200.102 192.168.0.0/24
• use_backend web2 if ip_range_test
• default_backend web1
• backend web1
• mode http
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
• backend web2
• mode http
• server web1 192.168.7.102:8080 check inter 2000 fall 3 rise 5
Acl示例-源地址访问控制
• listen web_port
• bind 192.168.7.102:8800
• mode http
• log global
• acl block_test src 192.168.7.103 192.168.7.104
• block if block_test
• default_backend web1
• backend web1
• mode http
• log global
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
Acl示例-匹配浏览器
• listen web_port
• bind 192.168.7.102:8800
• mode http
• log global
• acl block_test src 192.168.7.103 192.168.7.104
• acl redirect_test hdr(User-Agent) -m sub -i "Chrome"
• block if block_test
• redirect prefix http://192.168.7.101:8080 if redirect_test
• default_backend web2
• backend web1
• mode http
• log global
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
自定义错误页面
• errorfile 500 /usr/local/haproxy/html/500.html #自定义错误页面跳转
• errorfile 502 /usr/local/haproxy/html/502.html
• errorfile 503 /usr/local/haproxy/html/503.html
自定义错误跳转
• errorloc 503 http://192.168.7.103/error_page/503.html
基于acl+文件后缀实现动静分离
• listen web_port
• bind 192.168.7.102:80
• mode http
• acl php_server path_end -i .php
• use_backend php_server_host if php_server
• acl image_server path_end -i .jpg .png .jpeg .gif
• use_backend image_server_host if image_server
• default_backend default_host
• backend default_host
• mode http
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
• backend php_server_host
• mode http
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
• backend image_server_host
• mode http
• server web1 192.168.7.102:8080 check inter 2000 fall 3 rise 5
acl-匹配访问路径
• listen web_port
• bind 192.168.7.102:80
• mode http
• acl static_path path_beg -i /static /images /javascript
• use_backend static_path_host if static_path
• default_backend default_host
• backend default_host
• mode http
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
• backend static_path_host
• mode http
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
http 基于策略的访问控制
• listen web_port
• bind 192.168.7.102:80
• mode http
• acl badguy_deny src 192.168.4.1
• http-request deny if badguy_deny
• http-request allow
• default_backend default_host
• backend default_host
• mode http
• server web1 192.168.7.102:8080 check inter 2000 fall 3 rise 5
• backend static_path_host
• mode http
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
• backend image_server_host
• mode http
• server web1 192.168.7.102:8080 check inter 2000 fall 3 rise 5
预定义acl
• ACL name Equivalent to Usage
• FALSE always_false never match
• HTTP req_proto_http match if protocol is valid HTTP
• HTTP_1.0 req_ver 1.0 match HTTP version 1.0
• HTTP_1.1 req_ver 1.1 match HTTP version 1.1
• HTTP_CONTENT hdr_val(content-length) gt 0 match an existing content-length
• HTTP_URL_ABS url_reg ^[^/:]*:// match absolute URL with scheme
• HTTP_URL_SLASH url_beg / match URL beginning with "/"
• HTTP_URL_STAR url * match URL equal to "*"
• LOCALHOST src 127.0.0.1/8 match connection from local host
• METH_CONNECT method CONNECT match HTTP CONNECT method
• METH_DELETE method DELETE match HTTP DELETE method
• METH_GET method GET HEAD match HTTP GET or HEAD method
• METH_HEAD method HEAD match HTTP HEAD method
• METH_OPTIONS method OPTIONS match HTTP OPTIONS method
• METH_POST method POST match HTTP POST method
• METH_PUT method PUT match HTTP PUT method
• METH_TRACE method TRACE match HTTP TRACE method
• RDP_COOKIE req_rdp_cookie_cnt gt 0 match presence of an RDP cookie
• REQ_CONTENT req_len gt 0 match data in the request buffer
• TRUE always_true always match
• WAIT_END wait_end wait for end of content analysis
预定义acl使用
• listen web_port
• bind 192.168.7.102:80
• mode http
• acl static_path path_beg -i /static /images /javascript
• use_backend static_path_host if HTTP_1.1 TRUE static_path
• default_backend default_host
• backend default_host
• mode http
• server web1 192.168.7.102:8080 check inter 2000 fall 3 rise 5
• backend static_path_host
• mode http
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
四层负载
• Memcache
• Redis
• MySQL
• RabbitMQ
• Web Server
• ……
• listen redis-port
• bind 192.168.7.102:6379
• mode tcp
• balance leastconn
• server server1 192.168.7.103:6379 check
• server server2 192.168.7.104:6379 check backup
四层访问控制
• tcp-request connection {accept|reject} [{if | unless} <condition>] 根据第4层条件对传入连接执行操作
• listen redis-port
• bind 192.168.7.102:6379
• mode tcp
• balance leastconn
• acl invalid_src src 192.168.1.0/24 192.168.7.101
• tcp-request connection reject if invalid_src
• server server1 192.168.7.104:6379 check
• server server1 192.168.7.103:6379 check backup
HAProxy-https协议
• 配置HAProxy支持https协议:
• 支持ssl会话;
bind *:443 ssl crt /PATH/TO/SOME_PEM_FILE
crt 后证书文件为PEM格式,且同时包含证书和所有私钥
cat demo.crt demo.key > demo.pem
• 把80端口的请求重向定443
bind *:80
redirect scheme https if !{ ssl_fc }
• 向后端传递用户请求的协议和端口(frontend或backend)
http_request set-header X-Forwarded-Port %[dst_port]
http_request add-header X-Forwared-Proto https if { ssl_fc }
https-证书制作
• # mkdir /usr/local/haproxy/certs
• # cd /usr/local/haproxy/certs
• # openssl genrsa -out haproxy.key 2048
• # openssl req -new -x509 -key haproxy.key -out haproxy.crt -subj "/CN=www.magedu.net"
• # cat haproxy.key haproxy.crt > haproxy.pem
• # openssl x509 -in haproxy.pem -noout -text #查看证书
https 示例
• #web server http
• frontend web_server-http
• bind 172.18.200.101:80
• redirect scheme https if !{ ssl_fc }
• mode http
• use_backend web_host
• #web server https
• frontend web_server-https
• bind 172.18.200.101:443 ssl crt /usr/local/haproxy/certs/haproxy.pem
• mode http
• use_backend web_host
• backend default_host
• mode http
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
• server web2 192.168.7.102:8080 check inter 2000 fall 3 rise 5
• backend web_host
• mode http
• http-request set-header X-Forwarded-Port %[dst_port]
• http-request add-header X-Forwarded-Proto https if { ssl_fc }
• server web1 192.168.7.101:8080 check inter 2000 fall 3 rise 5
• server web2 192.168.7.102:8080 check inter 2000 fall 3 rise 5
HAProxy-服务器动态上下线
• # yum install socat
• # echo "show info" | socat stdio /var/lib/haproxy/haproxy.sock
• # echo "get weight web_host/192.168.7.101" | socat stdio /var/lib/haproxy/haproxy.sock
• # echo "disable server web_host/192.168.7.101" | socat stdio /var/lib/haproxy/haproxy.sock
• # echo "enable server web_host/192.168.7.101" | socat stdio /var/lib/haproxy/haproxy.sock
HAProxy-实战案例
• 编写shell脚本,实现能传递多个后端服务器IP为脚本参数,并ssh到haproxy
服务器中动态将后端server逐个开启和关闭。