一、HAProxy的安装
1、Centos安装:
yum install haproxy
2、Ubuntu 安装:
apt-get install haproxy
3、编译安装
(1)#安装前准备
yum install gcc gcc-c++ glibc glibc-devel pcre pcre-devel openssl openssl-devel systemd-devel net-tools vim iotop bc zip unzip zlib-devel lrzsz tree screen lsof tcpdump wget ntpdate
(2)#下载及解压
tar xvf haproxy-1.8.16.tar.gz && cd haproxy-1.8.16
(3)#编译安装
make ARCH=x86_64 TARGET=linux2628 USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_CPU_AFFINITY=1 PREFIX=/usr/local/haproxy
(4)#编译安装
make install PREFIX=/usr/local/haproxy
(5)#将haproxy命令放至/usr/sbin/下
cp haproxy /usr/sbin/
(6)#创建启动脚本:
vim /usr/lib/systemd/system/haproxy.service
[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target
[Service]
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID
[Install]
WantedBy=multi-user.target
(7)#创建目录和用户:
mkdir /etc/haproxy
useradd haproxy -s /sbin/nologin
mkdir /var/lib/haproxy
chown haproxy.haproxy /var/lib/haproxy/ -R
(8)#编辑配置文件
vim /etc/haproxy/haproxy.cfg
……
(9)#启动服务
systemctl enable haproxy && systemctl restart haproxy
二、HAproxy常用配置选项中文注释
1、global配置:
官方网站:https://cbonte.github.io/haproxy-dconv/1.8/configuration.html#3
• chroot #锁定运行目录
• deamon #以守护进程运行
• #stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin #socket文件
• user, group, uid, gid #运行haproxy的用户身份
• nbproc #开启的haproxy进程数,与CPU保持一致
• nbthread #指定每个haproxy进程开启的线程数,默认为每个进程一个线程
• cpu-map 1 0 #绑定haproxy 进程至指定CPU
• maxconn #每个haproxy进程的最大并发连接数
• maxsslconn #SSL每个haproxy进程ssl最大连接数
• maxconnrate #每个进程每秒最大连接数
• spread-checks #后端server状态check随机提前或延迟百分比时间,建议2-5(20%-50%)之间
• pidfile #指定pid文件路径
• log 127.0.0.1 local3 info #定义全局的syslog服务器;最多可以定义两个
2、Proxies配置:
defaults 配置参数:
• option redispatch #当server Id对应的服务器挂掉后,强制定向到其他健康的服务器
• option abortonclose #当服务器负载很高的时候,自动结束掉当前队列处理比较久的链接
• option http-keep-alive 60#开启会话保持
• option forwardfor #开启IP透传
• mode http #默认工作类型
• timeout connect 120s #转发客户端请求到后端server的最长连接时间(TCP之前)
• timeout server 600s #转发客户端请求到后端服务端的超时时长(TCP之后)
• timeout client 600s #与客户端的最长空闲时间
• timeout http-keep-alive 120s #session 会话保持超时时间,范围内会转发到相同的后端服务器
• #timeout check 5s #对后端服务器的检测超时时间
frontend配置参数:
backend配置参数:
#frontend/ backend 配置案例:
frontend WEB_PORT_80
bind 192.168.7.248:80
mode http
use_backend web_prot_http_nodes
backend web_prot_http_nodes
mode http
option forwardfor
server 192.168.7.101 192.168.7.101:8080 check inter 3000 fall 3 rise 5
server 192.168.7.102 192.168.7.102:8080 check inter 3000 fall 3 rise 5
listen配置参数:
#使用listen替换frontend和backend的配置方式:
listen WEB_PORT_80
bind 192.168.7.102:80 #指定HAProxy的监听地址
mode http #七层代理,可代理http协议,centos中实际的默认模式
#mode tcp #四层代理,可代理mysql/pgsql/ssh/ssl等协议,https时使用,默认模式
#health #回应ok后断开连接,较少使用
option forwardfor
server web1 192.168.7.101:8080 check inter 3000 fall 3 rise 5 #定义后端real server
server web2 192.168.7.101:8080 check inter 3000 fall 3 rise 5 #check:对指定real server的8080端口进行健康状态检查,每3000ms检查一次,连续3次检测失败标记不可用,连续检测5次成功标记可用。
3、balance:
指明对后端服务器的调度算法,配置在listen或backend
(1)静态调度算法:
按照事先定义好的规则轮询公平调度,不关心后端服务器的当前负载、链接数和相应速度等,且无法实时修改权重,只能重启后生效。
static-rr:
#基于权重的轮询调度,不支持权重的运行时调整及后端服务器慢启动,其后端主机数量没有限制
first:
#根据服务器在列表中的位置,自上而下进行调度,但是其只会当第一台服务器的连接数达到上限,新请求才会分配给下一台服务,因此会忽略服务器的权重设置。
#取决于hash_type是否consistent:
#mode http #不支持tcp,会切换到tcp的roundrobin负载模式(source支持tcp/http)
#balance source/uri/url_param/hdr/rdp-cookie
#hash-type consistent
source:
#后续同一个源地址请求将被转发至同一个后端web服务器
#源地址hash,基于用户源地址hash并将请求转发到后端服务器,默认为静态即取模方式,但是可以通过hash-type支持的选项更改,后续同一个源地址请求将被转发至同一个后端web服务器,比较适用于session保持/缓存业务等场景。
uri:
#curl http://192.168.7.101/index.html或test.html
#基于对用户请求的uri做hash并将请求转发到后端指定服务器
url_param name: #基于参数name做hash
#http://www.magedu.com/foo/bar/index.php?k1=v1&k2=v2
#url_param = "k1=v1&k2=v2"
#对用户请求的url中的<params>部分中的参数name作hash计算,并由服务器总权重相除以后派发至某挑出的服务器;通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个Backend Server
hdr(<name>):
#不同的浏览器被调度到不同的web服务器,hdr( Cookie、 User-Agent、host)
#针对用户每个http头部(header)请求中的指定信息做hash,此处由<name>指定的http首部将会被取出并做hash计算,然后由服务器总权重相除以后派发至某挑出的服务器,假如无有效的值,则会被轮询调度
rdp-cookie(<name>):
#对远程桌面的负载,使用cookie保持会话
(2)动态调度算法:
基于后端服务器状态进行调度适当调整,比如优先调度至当前负载较低的服务器,且权重可以在haproxy运行时动态调整无需重启
roundrobin:
#基于权重的轮询动态调度算法,支持权重的运行时调整,不等于lvs的rr,支持慢启动即新加的服务器会逐渐增加转发数,每个后端backend中最多支持4095个server,此为默认调度算法,server 权重设置 weight
leastconn:
#加权的最少连接的动态,支持权重的运行时调整和慢启动,即当前后端服务器连接最少的优先调度,比较适合长连接的场景使用,比如MySQL等场景。
(3)hash_type
map-based:取模法
#基于服务器权重的hash数组取模,该hash是静态的即不支持在线调整权重,不支持慢启动,其对后端服务器调度均衡,缺点是当服务器的总权重发生变化时,即有服务器上线或下线,都会因权重发生变化而导致调度结果整体改变,hash(o)mod n 。
consistent:一致性hash
#该hash是动态的,支持在线调整权重,支持慢启动,优点在于当服务器的总权重发生变化时,对调度结果影响是局部的,不会引起大的变动。
4、Cookie 配置
cookie <name> [ rewrite | insert | prefix ] [ indirect ] [ nocache ] [ postonly ] [ preserve ] [ httponly ] [ secure ] [ domain <domain> ]* [ maxidle <idle> ] [ maxlife <life> ]:
#为当前server指定cookie值,实现基于cookie的会话黏性
5、状态页stats配置
• stats enable #基于默认的参数启用stats page
• stats hide-version # 隐藏版本
• stats refresh <delay> # 设定自动刷新时间间隔
• stats uri <prefix> #自定义stats page uri,默认值:/haproxy?stats
• stats realm <realm> #账户认证时的提示信息,示例:stats realm : HAProxy\ Statistics
• stats auth <user>:<passwd> #认证时的账号和密码,可使用多次,默认:no authentication
• stats admin { if | unless } <cond> #启用stats page中的管理功能
6、报文首部修改配置
reqadd <string> [{if | unless} <cond>]:
#示例:rspadd X-Via:\ HAPorxy
reqdel <search> [{if | unless} <cond>]:
#示例: rspidel server.* #从相应报文删除server信息
7、日志配置
#在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:
log global
#验证:
tail /var/log/haproxy.log
#自定义日志的详细信息:
capture cookie <name> len <length>
#捕获请求和响应报文中的 cookie并记录日志
capture request header <name> len <length>
#捕获请求报文中指定的首部内容和长度并记录日志
capture response header <name> len <length>
#捕获响应报文中指定的内容和长度首部并记录日志
8、压缩功能compression:
compression algo #启用http协议中的压缩机制,常用算法有gzip deflate
compression type #要压缩的类型
9、Web服务器状态监测:
#三种状态监测方式:
#基于四层的传输端口做状态监测
server 172.18.200.103 172.18.200.103:80 check inter 3s fall 3 rise 5 weight 1
#基于指定URI做状态监测
#option httpchk <method> <uri> <version>
option httpchk GET /wp-includes/js/jquery/jquery.js?ver=1.12.4 HTTP/1.0
#基于指定URI的request请求头部内容做状态监测
option httpchk HEAD /wp-includes/js/jquery/jquery.js?ver=1.12.4 HTTP/1.0\r\nHost:\ 192.168.7.102
10、ACL配置
对接收到的报文进行匹配和过滤,基于请求报文头部中的源地址、源端口、目标地址、目标端口、请求方法、URL、文件后缀等信息内容进行匹配并执行进一步操作。
acl <aclname> <criterion> [flags] [operator] [<value>]
#acl 名称 条件 条件标记位 具体操作符 操作对象类型
#acl image_service hdr_dom(host) -i img.magedu.com
1、<aclname>名称:
可以使用字母、数字0-9、冒号:、点.、中横线和下划线,并且严格区分大小写
2、<criterion>:
• 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>]])#子串匹配
3、<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
4、<flags>-条件标记位:
• -i #不区分大小写
• -m #使用指定的pattern匹配方法
• -n #不做DNS解析
• -u #禁止acl重名,否则多个同名ACL匹配或关系
5、[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进行匹配
6、<value>操作对象类型:
• Boolean #布尔值
• integer or integer range #整数或整数范围,比如用于匹配端口范围
• IP address / network #IP地址或IP范围, 192.168.0.1 ,192.168.0.1/24
• string
exact #精确比较
substring#子串 www.magedu.com
suffix#后缀比较
prefix#前缀比较
subdir#路径, /wp-includes/js/jquery/jquery.js
domain#域名,www.magedu.com
• regular expression #正则表达式
• hex block #16进制
11、自定义错误页面errorfile,errorloc
errorfile 500 /usr/local/haproxy/html/500.html #自定义错误页面
errorloc 503 http://192.168.7.103/error_page/503.html #自定义错误跳转
12、HAProxy-https协议
#把80端口的请求重向定443
bind *:80
redirect scheme https if !{ ssl_fc }
#支持ssl会话
bind *:443 ssl crt /PATH/TO/SOME_PEM_FILE
#向后端传递用户请求的协议和端口(frontend或backend)
http_request set-header X-Forwarded-Port %[dst_port]
http_request add-header X-Forwared-Proto https if { ssl_fc }