反向代理软件之HAproxy基础

负载均衡:Load Balance,简称LB,是一种服务或基于硬件设备等实现的高可用反向代理技术,负载均
衡将特定的业务(web服务、网络流量等)分担给指定的一个或多个后端特定的服务器或设备,从而提高了
公司业务的并发处理能力、保证了业务的高可用性、方便了业务后期的水平动态扩展

为什么使用负载均衡

Web服务器的动态水平扩展-->对用户无感知
增加业务并发访问及处理能力-->解决单服务器瓶颈问题
节约公网IP地址-->降低IT支出成本
隐藏内部服务器IP-->提高内部服务器安全性
配置简单-->固定格式的配置文件
功能丰富-->支持四层和七层,支持动态下线主机
性能较强-->并发数万甚至数十万

负载均衡类型

四层:
LVS:Linux Virtual Server
Nginx:1.9版之后
HAProxy:High Availability Proxy

七层:
HAProxy
Nginx

硬件:

F5 https://f5.com/zh
Netscaler https://www.citrix.com.cn/products/citrix-adc/
Array https://www.arraynetworks.com.cn/
深信服 http://www.sangfor.com.cn/
北京灵州 http://www.lingzhou.com.cn/cpzx/llfzjh/

应用场景

四层:Redis、Mysql、RabbitMQ、Memcache等
七层:Nginx、Tomcat、Apache、PHP、图片、动静分离、API等

HAProxy是法国开发者威利塔罗(Willy Tarreau) 在2000年使用C语言开发的一个开源软件,是一款具
备高并发(一万以上)、高性能的TCP和HTTP负载均衡器,支持基于cookie的持久性,自动故障切换,支
持正则表达式及web状态统计,目前最新TLS版本为2.4

企业版网站:https://www.haproxy.com/

社区版网站:http://www.haproxy.org/
github:https://github.com/haproxy

HAproxy支持功能:

TCP 和 HTTP反向代理
SSL/TSL服务器
可以针对HTTP请求添加cookie,进行路由后端服务器
可平衡负载至后端服务器,并支持持久连接
支持所有主服务器故障切换至备用服务器
支持专用端口实现监控服务
支持停止接受新连接请求,而不影响现有连接
可以在双向添加,修改或删除HTTP报文首部
响应报文压缩
支持基于pattern实现连接请求的访问控制
通过特定的URI为授权用户提供详细的状态信息
支持http反向代理
支持动态程序的反向代理
支持基于数据库的反向代理

不具备的功能:

正向代理--squid,nginx
缓存代理--varnish
web服务--nginx、tengine、apache、php、tomcat
UDP--目前不支持UDP协议
单机性能--相比LVS性能较差

HAProxy 支持基于lua实现功能扩展,lua是一种小巧的脚本语言,于1993年由巴西里约热内卢天主教大学(Pontifical Catholic University of Rio de Janeiro)里的一个研究小组开发,其设计目的是为了嵌入
应用程序中,从而为应用程序提供灵活的扩展和定制功能。

范例:CentOS 7 安装haproxy

[root@centos7 ~]# yum install haproxy -y

范例:CentOS 8 安装haproxy

[root@centos8 ~]# dnf -y install haproxy

第三方安装包
官方没有提供rpm相关的包,可以通过第三方仓库的rpm包

从第三方网站下载rpm包:https://pkgs.org/download/haproxy

范例:

[root@centos8 ~]# wget http://www.nosuchhost.net/~cheese/fedora/packages/epel-7/x86_64/cheeserelease-7-1.noarch.rpm
[root@centos8 ~]# rpm -ivh cheese-release-7-1.noarch.rpm
[root@centos8 ~]# yum install haproxy

范例:利用第三方 yum 仓库安装

[root@centos7 ~]# wget https://centos7.iuscommunity.org/ius-release.rpm
[root@centos7 ~]# rpm -Uvh ius-release*rpm
[root@centos7 ~]# yum -y install epel-release
[root@centos7 ~]# rpm -Uvh ius-release*rpm
[root@centos7 ~]# yum install haproxy

范例:下载rpm包离线安装

#下载安装lua库对应的版本
[root@centos7 ~]# wget
https://dl.iuscommunity.org/pub/ius/stable/CentOS/7/x86_64/lua53u-libs-5.3.4-1.ius.centos7.x86_64.rpm
#安装lua库
[root@centos7 ~]# yum -y install lua53u-libs-5.3.4-1.ius.centos7.x86_64.rpm
#下载haproxy
[root@centos7 ~]# wget
https://dl.iuscommunity.org/pub/ius/stable/CentOS/7/x86_64/haproxy18u-1.8.20-
1.el7.ius.x86_64.rpm
#安装haproxy
[root@centos7 ~]# yum -y install haproxy18u-1.8.20-1.el7.ius.x86_64.rpm

编译安装HAproxy

# 依赖包
[root@centos8 ~]# yum install gcc readline-devel
下载lua包
[root@centos8 ~]# wget http://www.lua.org/ftp/lua-5.3.5.tar.gz
[root@centos8 ~]# tar xf lua-5.3.5.tar.gz -C /usr/local/src/
[root@centos8 ~]# cd /usr/local/src/lua-5.3.5/
[root@centos8 ~]# make linux test

# 查看lua安装的版本
[root@centos8 ~]# /usr/local/src/lua-5.3.5/src/lua -v
# 依赖包
[root@centos8 ~]# yum -y install gcc openssl-devel pcre-devel systemd-devel readline-devel
[root@centos8 ~]# tar xf haproxy-2.1.3.tar.gz -C /usr/local/src/
[root@centos8 ~]# cd /usr/local/src/haproxy-2.1.3/
[root@centos8 ~]# make ARCH=x86_64 TARGET=linux-glibc USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_LUA=1 LUA_INC=/usr/local/src/lua-5.3.5/src/ LUA_LIB=/usr/local/src/lua-5.3.5/src/

[root@centos8 ~]# make install PREFIX=/apps/haproxy
[root@centos8 ~]# ln -s /apps/haproxy/sbin/haproxy /usr/sbin/

# 查看haproxy安装的版本
[root@centos8 ~]# haproxy -v

启动文件

[root@centos8 ~]# 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 /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID
LimitNOFILE=100000

[Install]
WantedBy=multi-user.target

重新加载

[root@centos8 ~]# systemctl daemon-reload
[root@centos8 ~]# systemctl start haproxy

# 创建两个文件夹
[root@centos8 ~]# mkdir /etc/haproxy
[root@centos8 ~]# mkdir /var/lib/haproxy

配置文件

[root@centos8 ~]# vim /etc/haproxy/haproxy.cfg
global
    maxconn 100000
    chroot /apps/haproxy
    stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
    uid 99
    gid 99
    user haproxy
    group haproxy
    daemon
    #nbproc 4
    #cpu-map 1 0
    #cpu-map 2 1
    #cpu-map 3 2
    #cpu-map 4 3
    pidfile /var/lib/haproxy/haproxy.pid
    log 127.0.0.1 local2 info

defaults
    option http-keep-alive
    option forwardfor
    maxconn 100000
    mode http
    timeout connect 300000ms
    timeout client 300000ms
    timeout server 300000ms

listen stats
    mode http
    bind 0.0.0.0:9999
    stats enable
    log global
    stats uri /status
    stats auth haadmin:123456
listen web_port
    bind 172.31.0.28:80
    mode http
    log global
    #server web1 127.0.0.1:8080 check inter 3000 fall 2 rise 5  
    server 172.31.0.17 172.31.0.17:80 check inter 3000 fall 2 rise 5  # 这是后端的web服务器,必须要有
    server 172.31.0.27 172.31.0.27:80 check inter 3000 fall 2 rise 5  # 这是后端的web服务器,必须要有

haproxy.cfg文件中定义了chroot、pidfile、user、group等参数,如果系统没有相应的资源会导致
haproxy无法启动,具体参考日志文件 /var/log/messages

[root@centos8 ~]# journalctl -xe

Jun 22 05:08:24 centos8.longxuan.vip haproxy[10959]: [ALERT] 172/050824 (10959) : Cannot open configuration file/directory /etc/haproxy/haproxy.cfg : No such file or direct
Jun 22 05:08:24 centos8.longxuan.vip systemd[1]: haproxy.service: Control process exited, code=exited status=1
Jun 22 05:08:24 centos8.longxuan.vip systemd[1]: haproxy.service: Failed with result 'exit-code'.

Jun 22 05:12:13 centos8.longxuan.vip systemd[1]: Starting HAProxy Load Balancer...
Jun 22 05:12:13 centos8.longxuan.vip haproxy[10974]: [ALERT] 172/051213 (10974) : parsing [/etc/haproxy/haproxy.cfg:7] : cannot find user id for 'haproxy' (0:Success)
Jun 22 05:12:13 centos8.longxuan.vip haproxy[10974]: [ALERT] 172/051213 (10974) : parsing [/etc/haproxy/haproxy.cfg:8] : cannot find group id for 'haproxy' (0:Success)
Jun 22 05:12:13 centos8.longxuan.vip haproxy[10974]: [ALERT] 172/051213 (10974) : Error(s) found in configuration file : /etc/haproxy/haproxy.cfg
Jun 22 05:12:13 centos8.longxuan.vip haproxy[10974]: [ALERT] 172/051213 (10974) : Fatal errors found in configuration.

查看haproxy的状态页面

浏览器访问: http://haproxy-server:9999/status

基础配置详解

官方文档:

http://cbonte.github.io/haproxy-dconv/

# 带版本的(2.1版本)
http://cbonte.github.io/haproxy-dconv/2.1/configuration.html

HAProxy 的配置文件haproxy.cfg由两大部分组成,分别是global和proxies部分

global:全局配置段

进程及安全配置相关的参数
性能调整相关参数
Debug参数

proxies:代理配置段

defaults:为frontend, backend, listen提供默认配置
frontend:前端,相当于nginx中的server {}
backend:后端,相当于nginx中的upstream {}
listen:同时拥有前端和后端配置,配置简单,生产推荐使用

global 配置参数说明

官方文档:http://cbonte.github.io/haproxy-dconv/2.4/configuration.html#3

chroot #锁定运行目录
deamon #以守护进程运行
stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin process 1
#socket文件
user, group, uid, gid #运行haproxy的用户身份
nbproc n #开启的haproxy worker 进程数,默认进程数是一个
#nbthread 1 #和多进程 nbproc配置互斥(版本有关,CentOS8的haproxy1.8无此问题),指定每
个haproxy进程开启的线程数,默认为每个进程一个线程
#如果同时启用nbproc和nbthread 会出现以下日志的错误,无法启动服务
Apr 7 14:46:23 haproxy haproxy: [ALERT] 097/144623 (1454) : config : cannot
enable multiple processes if multiple threads are configured. Please use either
nbproc or nbthread but not both.
cpu-map 1 0 #绑定haproxy worker 进程至指定CPU,将第1个work进程绑定至0号CPU
cpu-map 2 1 #绑定haproxy worker 进程至指定CPU,将第2个work进程绑定至1号CPU
maxconn n #每个haproxy进程的最大并发连接数
maxsslconn n #每个haproxy进程ssl最大连接数,用于haproxy配置了证书的场景下
maxconnrate n #每个进程每秒创建的最大连接数量
spread-checks n #后端server状态check随机提前或延迟百分比时间,建议2-5(20%-50%)之间,默认
值0
pidfile #指定pid文件路径
log 127.0.0.1 local2 info #定义全局的syslog服务器;日志服务器需要开启UDP协议,最多可以定
义两个

多进程和线程

范例:多进程和socket文件

[root@centos7 ~]# vim /etc/haproxy/haproxy.cfg
global
    maxconn 100000
    chroot /apps/haproxy
    stats socket /var/lib/haproxy/haproxy.sock1 mode 600 level admin process 1
    stats socket /var/lib/haproxy/haproxy.sock2 mode 600 level admin process 2
    uid 99
    gid 99
    daemon
    nbproc 2
    
[root@centos7 ~]# systemctl restart haproxy
[root@centos7 ~]# pstree -p |grep haproxy
               |-haproxy(2688)-+-haproxy(2690)
               |               `-haproxy(2691)
               
[root@centos7 ~]# ll /var/lib/haproxy/
total 4
-rw-r--r-- 1 root root 5 Mar 31 10:49 haproxy.pid
srw------- 1 root root 0 Mar 31 10:49 haproxy.sock1
srw------- 1 root root 0 Mar 31 10:49 haproxy.sock2

HAProxy日志配置

HAproxy本身不记录客户端的访问日志.此外为减少服务器负载,一般生产中HAProxy不记录日志.
也可以配置HAProxy利用rsyslog服务记录日志到指定日志文件中

HAProxy配置

[root@centos7 ~]# vim /etc/haproxy/haproxy.cfg
#在global配置项定义:
log 127.0.0.1 local{1-7} info #基于syslog记录日志到指定设备,级别有(err、warning、
info、debug)
listen web_port
bind 127.0.0.1:80
mode http
log global #开启当前web_port的日志功能,默认不记录日
志
server web1 127.0.0.1:8080 check inter 3000 fall 2 rise 5

[root@centos7 ~]# systemctl restart haproxy

Rsyslog配置(CentOS7版本的写法)生产不推荐haproxy记录日志,这样会加大haproxy负载

[root@centos7 ~]# vim /etc/rsyslog.conf
$ModLoad imudp
$UDPServerRun 514
......
local3.* /var/log/haproxy.log
......
[root@centos7 ~]# systemctl restart rsyslog

重启syslog服务并访问app页面,然后验证是否生成日志

[root@centos8 ~]# tail -f /var/log/haproxy.log
Jun 22 19:01:09 localhost haproxy[11406]: Connect from 172.31.0.29:50626 to 172.31.0.28:80 (web_port/HTTP)

Proxies配置

官方文档:http://cbonte.github.io/haproxy-dconv/2.1/configuration.html#4

defaults [<name>] #默认配置项,针对以下的frontend、backend和listen生效,可以多个name也可
以没有name
frontend <name> #前端servername,类似于Nginx的一个虚拟主机 server和LVS服务集群。
backend <name> #后端服务器组,等于nginx的upstream和LVS中的RS服务器
listen <name> #将frontend和backend合并在一起配置,相对于frontend和backend配置更简
洁,生产常用

注意:name字段只能使用大小写字母,数字,‘-’(dash),'_‘(underscore),'.' (dot)和 ':'(colon),并且严格区分大小写

Proxies配置-defaults

option redispatch #当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派
发
option abortonclose #当服务器负载很高时,自动结束掉当前队列处理比较久的连接,针对业务情
况选择开启
option http-keep-alive #开启与客户端的会话保持
option forwardfor #透传客户端真实IP至后端web服务器
mode http|tcp #设置默认工作类型,使用TCP服务器性能更好,减少压力
timeout http-keep-alive 120s #session 会话保持超时时间,此时间段内会转发到相同的后端服务
器
timeout connect 120s #客户端请求从haproxy到后端server最长连接等待时间(TCP连接之前),
默认单位ms
timeout server 600s #客户端请求从haproxy到后端服务端的请求处理超时时长(TCP连接之后),
默认单位ms,如果超时,会出现502错误,此值建议设置较大些,访止502错误
timeout client 600s #设置haproxy与客户端的最长非活动时间,默认单位ms,建议和timeout
server相同
timeout check 5s #对后端服务器的默认检测超时时间
default-server inter 1000 weight 3 #指定后端服务器的默认设置

Proxies配置-listen 简化配置

使用listen替换 frontend和backend的配置方式,可以简化设置,通常只用于TCP协议的应用

#官网业务访问入口
listen WEB_PORT_80
    bind 10.0.0.7:80
    mode http
    option forwardfor
    server web1 172.31.0.17:8080 check inter 3000 fall 3 rise 5
    server web2 172.31.0.27:8080 check inter 3000 fall 3 rise 5

Proxies配置-frontend

bind: #指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于
listen字段中
#格式:
bind [<address>]:<port_range> [, ...] [param*]
#注意:如果需要绑定在非本机的IP,需要开启内核参数:net.ipv4.ip_nonlocal_bind=1
backlog <backlog> #针对所有server配置,当前端服务器的连接数达到上限后的后援队列长度,注意:不支持backend

范例:

listen http_proxy #监听http的多个IP的多个端口和sock文件
    bind :80,:443,:8801-8810
    bind 171.31.0.1:10080,172.31.0.1:10443
    bind /var/run/ssl-frontend.sock user root mode 600 accept-proxy
    
listen http_https_proxy #https监听
    bind :80
    bind :443 ssl crt /etc/haproxy/site.pem #公钥和私钥公共文件
    
listen http_https_proxy_explicit #监听ipv6、ipv4和unix sock文件
    bind ipv6@:80
    bind ipv4@public_ssl:443 ssl crt /etc/haproxy/site.pem
    bind unix@ssl-frontend.sock user root mode 600 accept-proxy
    
listen external_bind_app1 #监听file descriptor
    bind "fd@${FD_APP1}"

生产示例:

frontend magedu_web_port #可以采用后面形式命名:业务-服务-端口号
    bind :80,:8080
    bind 172.31.0.7:10080,:8801-8810,172.31.0.17:9001-9010
    mode http|tcp #指定负载协议类型
    use_backend <backend_name> #调用的后端服务器组名称

Proxies配置-backend

定义一组后端服务器,backend服务器将被frontend进行调用。
注意: backend 的名称必须唯一,并且必须在listen或frontend中事先定义才可以使用,否则服务无法启动

mode http|tcp #指定负载协议类型,和对应的frontend必须一致
option #配置选项
server #定义后端real server,必须指定IP和端口

注意:option后面加 httpchk,smtpchk,mysql-check,pgsql-check,ssl-hello-chk方法,可用于实现更多应用层检测功能。

server 配置
#针对一个server配置
check #对指定real进行健康状态检查,如果不加此设置,默认不开启检查,只有check后面没有其它配置也可以启用检查功能
#默认对相应的后端服务器IP和端口,利用TCP连接进行周期性健康性检查,注意必须指定端口才能实现健康性检查
addr <IP>  #可指定的健康状态监测IP,可以是专门的数据网段,减少业务网络的流量
port <num> #指定的健康状态监测端口
inter <num> #健康状态检查间隔时间,默认2000 ms
fall <num> #后端服务器从线上转为线下的检查的连续失效次数,默认为3
rise <num> #后端服务器从下线恢复上线的检查的连续有效次数,默认为2
weight <weight> #默认为1,最大值为256,0(状态为蓝色)表示不参与负载均衡,但仍接受持久连
接
backup   #将后端服务器标记为备份状态,只在所有非备份主机down机时提供服务,类似
Sorry Server
disabled #将后端服务器标记为不可用状态,即维护状态,除了持久模式,将不再接受连接,状态为深黄色,优雅下线,不再接受新用户的请求
redirect prefix http://www.baidu.com/ #将请求临时(302)重定向至其它URL,只适用于http模式
redir http://www.baidu.com #将请求临时(302)重定向至其它URL,只适用于http模式
maxconn <maxconn>  #当前后端server的最大并发连接数

frontend+backend 配置实例

frontend longxuan-test-http
    bind :80,:8080
    mode tcp
    use_backend longxuan-test-http-nodes
    
backend longxuan-test-http-nodes
    mode tcp
    default-server inter 1000 weight 6
    server web1 172.31.0.17:80 weight 2 check addr 172.31.0.117 port 8080
    server web1 172.31.0.27:80 check

范例2:

#官网业务访问入口
frontend WEB_PORT_80
    bind 10.0.0.7:80
    mode http
    use_backend web_prot_http_nodes
    
backend web_prot_http_nodes
    mode http
    option forwardfor
    server 10.0.0.17 10.0.0.17:8080 check inter 3000 fall 3 rise 5
    server 10.0.0.27 10.0.0.27:8080 check inter 3000 fall 3 rise 5

使用子配置文件保存配置

当业务众多时,将所有配置都放在一个配置文件中,会造成维护困难。可以考虑按业务分类,将配置信
息拆分,放在不同的子配置文件中,从而达到方便维护的目的。
注意: 子配置文件的文件后缀必须为.cfg

#创建子配置目录
[root@centos7 ~]# mkdir /etc/haproxy/conf.d/
#创建子配置文件,注意:必须为cfg后缀非.开头的配置文件
[root@centos7 ~]# vim /etc/haproxy/conf.d/test.cfg
listen WEB_PORT_80
    bind 172.31.0.7:80
    mode http
    balance roundrobin
    server web1 172.31.0.17:80 check inter 3000 fall 2 rise 5
    server web2 172.31.0.27:80 check inter 3000 fall 2 rise 5

#添加子配置目录到unit文件中
[root@centos7 ~]# vim /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 -f /etc/haproxy/conf.d/ -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -f /etc/haproxy/conf.d/ -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID

[Install]
WantedBy=multi-user.target

#重新加载并启动
[root@centos7 ~]# systemctl daemon-reload
[root@centos7 ~]# systemctl restart haproxy
原文地址:https://www.cnblogs.com/xuanlv-0413/p/15037087.html