haproxy

发布于:2025-07-31 ⋅ 阅读:(19) ⋅ 点赞:(0)

一、haproxy的简介

HAProxy 是一款高性能、开源的负载均衡器和反向代理服务器,主要用于 HTTP、HTTPS、TCP 等协议的流量分发,广泛应用于高并发的 Web 服务架构中,以提升系统的可用性、扩展性和稳定性

二、负载均衡

1、什么是负载均衡

负载均衡(Load Balancing)是一种网络技术或架构设计,核心目的是将大量客户端请求或网络流量 “均匀地” 分配到多个后端服务器(或资源节点)上,以避免单台服务器过载,提升系统整体的可用性、稳定性和处理效率。

2、负载均衡类型

四层负载均衡

四层负载均衡的工作原理是:

接收客户端发送的数据包,解析其中的源 IP、目标 IP、源端口、目标端口等传输层信息。
根据预设的负载均衡算法(如轮询、加权轮询、IP 哈希等),将请求转发到后端服务器集群中的某一台服务器。(基于ip+port)
转发过程中可能会修改数据包的目标 IP 和端口,使请求最终到达选定的后端服务器。

支持四层负载均衡的软件有lvs(重量级),haproxy(模拟),nginx(轻量级)

四层是指OSI 七层网络模型中的传输层(Transport Layer),其核心是基于IP 地址和端口号进行负载均衡决策

七层负载均衡

支持七层代理的软件:Nginx、Haproxy

七层负载均衡中的 “七层” 指的是OSI 七层网络模型中的应用层(Application Layer),它是在传输层(四层)基础上,进一步深入到应用层协议的细节进行负载均衡决策,核心是基于应用层数据(如 HTTP 头部、URL、Cookie 等) 实现请求分发。(基于虚拟URL和主机IP)

3、四层和七层的区别

(1)工作层级与协议解析:

四层负载均衡工作在 OSI 模型的传输层(第四层),仅基于 TCP/UDP 协议的端口号和 IP 地址 进行流量转发。它不解析应用层数据(如 HTTP 头、URL、Cookie 等),仅根据 “源 IP + 端口”“目标 IP + 端口” 的组合规则分发请求。

七层负载均衡工作在 OSI 模型的应用层(第七层),可解析 应用层协议(如 HTTP/HTTPS、FTP 等) 的具体内容。它能识别请求中的 URL、请求头、Cookie、主机名等信息,基于这些细节制定更精细的转发规则。

(2)技术原理对比

四层负载均衡仅解析 IP 地址、端口号(TCP/UDP 报文头部),基于 IP: 端口的固定映射规则,类似 “数据包转发”,速度快,性能损耗低。典型工具:LVS、HAProxy(TCP 模式)、F5(四层模式

七层负载均衡解析 IP、端口 + 应用层数据(如 HTTP 头、URL、Cookie 等),基于应用层内容(如 URL 路径、请求参数、主机名)需解析应用层协议,处理逻辑更复杂,性能损耗略高。典型工具:HAProxy(HTTP 模式)、Nginx、Traefik、F5(七层模式)

(3)功能特性对比

四层负载均衡支持基础算法(轮询、权重、IP 哈希等,仅通过 IP 哈希实现(基于源 IP 绑定后端节点),简单检查(如端口是否存活、TCP 连接是否建立),不处理 SSL 加密 / 解密,需后端服务器自行处理,仅能按 IP: 端口转发,无法基于应用内容分流

七层负载均衡支持四层所有算法 + 基于应用层的自定义规则(如按 URL 路由),可通过 Cookie、URL 参数、请求头实现更灵活的会话保持,深度检查(如 HTTP 响应码是否为 200、响应内容是否符合预期),支持 SSL 终止(集中解密 HTTPS 请求),减轻后端服务器压力,可按 URL 路径(如 /api/user 转发到用户服务)、域名等转发

(4)适用场景

四层负载均衡需高性能、低延迟的场景;非 HTTP 协议的服务;对转发规则要求简单的场景。

典型案例:数据库集群(MySQL 主从复制)、邮件服务器(SMTP)、游戏服务器(UDP 协议)、视频流传输(TCP 长连接)。

七层负载均衡需基于应用内容分流的场景;HTTP/HTTPS 服务;需要复杂路由和会话管理的场景。典型案例:Web 服务(按 URL 路径转发到不同后端)、API 网关(微服务路由)、HTTPS 集中证书管理、CDN 节点流量分发。

总结

  • 四层负载均衡:轻量、高效,适合对性能要求高但规则简单的场景,相当于 “基于端口的流量分发器”。
  • 七层负载均衡:灵活、智能,适合需要解析应用内容的复杂场景,相当于 “基于内容的流量控制器”。

实际架构中,两者常结合使用(如 “四层负载均衡 + 七层负载均衡”),例如:用 LVS 做四层负载提升整体吞吐量,后端接 HAProxy/Nginx 做七层路由,兼顾性能和灵活性。

三、haproxy基本配置信息

  • 软件安装包: haproxy-2.4.22-3.el9_3.x86_64.rpm

  • 启动文件: /lib/systemd/system/haproxy.service

  • 主配置目录: /etc/haproxy/

  • 主配置文件: /etc/haproxy/haproxy.cfg

  • 子配置目录: /etc/haproxy/conf.d

haproxy.cfg由两大部分组成:global,proxies

1、global配置:全局配置段

(1)global 配置参数
global
log 127.0.0.1 local2 #定义全局的syslog服务器;日志服务器需要开启UDP协
议,最多可以定义两个
chroot /var/lib/haproxy #锁定运行目录
pidfile /var/run/haproxy.pid #指定pid文件
maxconn 100000 #指定最大连接数
user haproxy #指定haproxy的运行用户
group haproxy #指定haproxy的运行组
daemon #指定haproxy以守护进程方式运行
# turn on stats unix socket
stats socket /var/lib/haproxy/stats #指定haproxy的套接字文件
nbproc 2 #指定haproxy的work进程数量,默认是1个
cpu-map 1 0 #指定第一个work绑定第一个cpu核心
cpu-map 2 1 #指定第二个work绑定第二个cpu核心
nbthread 2 #指定haproxy的线程数量,默认每个进程一个线
程,此参数与nbproc互斥
maxsslconn 100000 #每个haproxy进程ssl最大连接数,用于haproxy
配置了证书的场景下
maxconnrate 100 #指定每个客户端每秒建立连接的最大数量
(2)多进程和线程
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
global
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 100000
user haproxy
group haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/haproxy.sock1 mode 600 level admin process 1 #
启用多个sock文件
stats socket /var/lib/haproxy/haproxy.sock2 mode 600 level admin process 2
nbproc 2 #启用多进程
cpu-map 1 0 #进程和cpu核心绑定防止cpu抖动从而减少系统资源消耗
cpu-map 2 1 #2 表示第二个进程,1表示第二个cpu核心
...下面内容省略 ...
查看多进程信息
haproxy haproxy]# pstree -p | grep haproxy
|-haproxy(4816)-+-haproxy(4820)
| `-haproxy(4821)
启用多线程
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 100000
user haproxy
group haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/haproxy.sock1 mode 600 level admin process 1 #
启用多个sock文件
stats socket /var/lib/haproxy/haproxy.sock2 mode 600 level admin process 2
#nbproc 2
#cpu-map 1 0
#cpu-map 2 1
nbthread 2 #启用多线程
多线程对比
未开启多线程
haproxy ~]# cat /proc/xxxx(haproxy子进程id)/status
...上面内容省略...
Threads: 1
...下面内容省略...
开启后
haproxy ~]# cat /proc/xxxx(haproxy子进程id)/status
...上面内容省略...
Threads: 2
...下面内容省略...

2、proxies:代理配置段

(1)defaults配置
defaults
mode http #HAProxy实例使用的连接协议
log global #指定日志地址和记录日志条目的
syslog/rsyslog日志设备
#此处的 global表示使用 global配置段中
设定的log值。
option httplog #日志记录选项,httplog表示记录与 HTTP
会话相关的各种属性值
#包括 HTTP请求、会话状态、连接数、源地
址以及连接时间等
option dontlognull #dontlognull表示不记录空会话连接日志
option http-server-close #等待客户端完整HTTP请求的时间,此处为等
待10s。
option forwardfor except 127.0.0.0/8 #透传客户端真实IP至后端web服务器
#在apache配置文件中加入:<br>%{XForwarded-For}i
#后在webserver中看日志即可看到地址透传
信息
option redispatch #当server Id对应的服务器挂掉后,强制定
向到其他健康的服务器,重新派发
option http-keep-alive #开启与客户端的会话保持
retries 3 #连接后端服务器失败次数
3.3.2.3 Proxies配置-frontend
frontend 配置参数:
frontend 配置示例:
timeout http-request 10s #等待客户端请求完全被接收和处理的最长时
间
timeout queue 1m #设置删除连接和客户端收到503或服务不可
用等提示信息前的等待时间
timeout connect 120s #设置等待服务器连接成功的时间
timeout client 600s #设置允许客户端处于非活动状态,即既不发
送数据也不接收数据的时间
timeout server 600s #设置服务器超时时间,即允许服务器处于既
不接收也不发送数据的非活动时间
timeout http-keep-alive 60s #session 会话保持超时时间,此时间段内
会转发到相同的后端服务器
timeout check 10s #指定后端服务器健康检查的超时时间
maxconn 3000
default-server inter 1000 weight 3
(2)frontend配置
frontend lee-webserver-80
bind 172.25.254.100:80        #bind:指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字
段中
mode http
use_backend lee-webserver-80-RS #调用backend的名称
(3)backend配置
#定义一组后端服务器,backend服务器将被frontend进行调用。
注意: backend 的名称必须唯一,并且必须在listen或frontend中事先定义才可以使用,否则服务无法
启动
backend lee-webserver-80-RS
mode http					#指定负载协议类型,和对应的frontend必须一致
server web1 192.168.0.101:80 check inter 3s fall 3 rise 5
server web2 192.168.0.102:80 check inter 3s fall 3 rise 5		#定义后端real server,必须指定IP和端口
(4)listen配置
#使用listen替换 frontend和backend的配置方式,可以简化设置,通常只用于TCP协议的应用
listen webserver_80
bind 172.25.254.100:80
mode http
option forwardfor
server webserver1 192.168.0.101:80 check inter 3s fall 3 rise 5
server webserver2 192.168.0.102:80 check inter 3s fall 3 rise 5

3、socat 工具

(1)简介

socat是一个多功能的网络工具,用于创建双向的数据通道,可以在两个地址之间转发数据。它类似于 Unix 中的cat命令,但适用于网络连接,因此被称为 "Socket CAT"。socat可以处理各种网络协议,包括 TCP、UDP、SSL、Unix 域套接字等,也可以与文件、设备、标准输入 / 输出进行交互。

(2)针对多进程处理方法
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
stats socket /var/lib/haproxy/stats1 mode 600 level admin process 1
stats socket /var/lib/haproxy/stats2 mode 600 level admin process 2
nbproc 2
cpu-map 1 0
cpu-map 2 1
...上面内容省略...
 
 
这样每个进程就会有单独的sock文件来进行单独管理
 
 
 
[root@haproxy ~]# ll /var/lib/haproxy/
总用量 0
srw------- 1 root root 0 8月 8 13:43 stats
srw------- 1 root root 0 8月 8 13:46 stats1
srw------- 1 root root 0 8月 8 13:46 stats2

4、haproxy的状态界面

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
listen stats
mode http
bind 0.0.0.0:8888
stats enable
log global
stats uri /haproxy-status
stats auth lee:lee
...下面内容省略...

四、haproxy的算法

算法总结
#静态
static-rr--------->tcp/http
first------------->tcp/http
#动态
roundrobin-------->tcp/http
leastconn--------->tcp/http
random------------>tcp/http
#以下静态和动态取决于hash_type是否consistent
source------------>tcp/http
Uri--------------->http
url_param--------->http
hdr--------------->ht

1、静态算法

静态算法:按照事先定义好的规则轮询公平调度,不关心后端服务器的当前负载、连接数和响应速度等,且无法实时修改权重(只能为01,不支持其它值),只能靠重启HAProxy生效
(1)static-rr:基于权重的轮询调度
不支持运行时利用socat进行权重的动态调整
不支持端服务器慢启动
其后端主机数量没有限制,相当于LVS中的 wrr
vim /etc/haproxy/haproxy.cfg
 
listen webcluster
        bind            *:80
        mode            http
        balance         static-rr
        server  web1    192.168.134.10:80 check inter 5s fall 3 weight 2
        server  web2    192.168.134.20:80 check inter 5s fall 3 weight 1
(2)first
根据服务器在列表中的位置,自上而下进行调度
其只会当第一台服务器的连接数达到上限,新请求才会分配给下一台服务
其会忽略服务器的权重设置,不支持用socat进行动态修改权重,可以设置0和1,可以设置其它值但无效
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
 
listen webcluster
        bind            *:80
        mode            http
        balance         first
        server  web1    192.168.134.10:80 maxconn 3 check inter 5s fall 3 rise 5
        server  web2    192.168.134.20:80 check inter 5s fall 3 rise 5
 
 
[root@haproxy ~]# systemctl restart haproxy.service

2、动态算法

基于后端服务器状态进行调度适当调整, 新请求将优先调度至当前负载较低的服务器权重可以在haproxy运行时动态调整无需重启

(1)roundrobin
1. 基于权重的轮询动态调度算法,
2. 支持权重的运行时调整,不同于lvs中的rr轮训模式,
3. HAProxy中的roundrobin支持慢启动(新加的服务器会逐渐增加转发数),
4. 其每个后端backend中最多支持4095个real server,
5. 支持对real server权重动态调整,
6. roundrobin为默认调度算法,此算法使用广泛
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
 
listen webcluster
        bind            *:80
        mode            http
        #balance        static-rr
        #balance        first
        balance         roundrobin
        server  web1    192.168.134.10:80 check inter 5s fall 3 rise 5 weight 1
        server  web2    192.168.134.20:80 check inter 5s fall 3 rise 5 weight 1
 
 
[root@haproxy ~]# systemctl restart haproxy.service
(2)动态调整权重 
[root@haproxy ~]# echo "set weight webcluster/web1 2" | socat stdio /var/lib/haproxy/stats
 
[root@haproxy ~]# echo "get weight webcluster/web1" | socat stdio /var/lib/haproxy/stats
2 (initial 1)
 
[root@haproxy ~]# echo "get weight webcluster/web2" | socat stdio /var/lib/haproxy/stats
1 (initial 1)
(3)leastconn
leastconn加权的最少连接的动态
支持权重的运行时调整和慢启动,即:根据当前连接最少的后端服务器而非权重进行优先调度(新客户
端连接)
比较适合长连接的场景使用,比如:MySQL等场景。
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
 
listen webcluster
        bind            *:80
        mode            http
        #balance        static-rr
        #balance        first
        #balance        roundrobin
        balance         leastconn
        server  web1    192.168.134.10:80 check inter 5s fall 3 rise 5 weight 1
        server  web2    192.168.134.20:80 check inter 5s fall 3 rise 5 weight 1
 
[root@haproxy ~]# systemctl restart haproxy.service

3、其他算法

其它算法即可作为静态算法,又可以通过选项成为动态算法

(1)source
基于用户源地址hash并将请求转发到后端服务器,同一个源地址请求将被转发到同一个后端服务器。
适用于session会话保持但不支持
cookie和缓存的场景源地址有两种转发客户端请求到后端服务器的服务器选取计算方式,分别是取模法
和一致性hash
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
 
listen webcluster
        bind            *:80
        mode            http
        #balance        static-rr
        #balance        first
        #balance        roundrobin
        #balance        leastconn
        balance         source
        server  web1    192.168.134.10:80 check inter 5s fall 3 rise 5 weight 1
        server  web2    192.168.134.20:80 check inter 5s fall 3 rise 5 weight 1
        
[root@haproxy ~]# systemctl restart haproxy.service

map-base 取模法

对source地址进行hash计算,再基于服务器总权重的取模,最终结果决定将此请求转发至对应的后端服务器。
是静态的,即不支持在线调整权重,不支持慢启动

 

listen webserver_80
bind 192.168.134.100:80
mode http
balance source
server webserver1 192.168.134.10:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.134.20:80 weight 1 check inter 3s fall 3 rise 5

一致性hash

hash算法是动态的,支持使用 socat等工具进行在线权重调整,支持慢启动

listen webserver_80
bind 192.168.134.100:80
mode http
balance source
hash-type consistent
server webserver1 192.168.134.10:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.134.20:80 weight 1 check inter 3s fall 3 rise 5

 

(2)uri

基于对用户请求的URI的左半部分或整个urihash,再将hash结果对总权重进行取模后,根据最终结果将请求转发到后端指定服务器,适用于后端是缓存服务器场景

默认是静态算法,也可以通过hash-type指定map-basedconsistent,来定义使用取模法还是一致性hash

取模法配置

listen webserver_80
bind 192.168.134.100:80
mode http
balance uri
server webserver1 192.168.134.10:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.134.20:80 weight 1 check inter 3s fall 3 rise 5

一致性hash配置 

listen webserver_80
bind 192.168.134.100:80
mode http
balance uri
hash-type consistent
server webserver1 192.168.134.10:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.134.20:80 weight 1 check inter 3s fall 3 rise 5

访问测试 

root@rs1 ~]# echo RS1 192.168.134.10 index1 > /var/www/html/index1.html
[root@rs1 ~]# echo RS1 192.168.134.10 index2 > /var/www/html/index2.html
[root@rs1 ~]# echo RS1 192.168.134.10 index3 > /var/www/html/index3.html
[root@rs2 ~]# echo RS1 192.168.134.20 index1 > /var/www/html/index1.html
[root@rs2 ~]# echo RS1 192.168.134.20 index2 > /var/www/html/index2.html
[root@rs2 ~]# echo RS1 192.168.134.20 index3 > /var/www/html/index3.html
[root@node10 ~]# curl 192.168.134.100/index.html
RS2 server - 192.168.134.20
[root@node10 ~]# curl 192.168.134.100/index1.html
RS1 192.168.134.10 index1
(3)url_param
url_param对用户请求的url中的 params 部分中的一个参数key对应的value值作hash计算,并由服务器总权重相除以后派发至某挑出的服务器,后端搜索同一个数据会被调度到同一个服务器,多用与电商通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个real server
#假设:
url = http://www.timinglee.com/foo/bar/index.php?key=value
#则:
host = "www.timinglee.com"
url_param = "key=value"

url_param取模法 

listen webserver_80
bind 192.168.134.100:80
mode http
balance url_param name,userid #支持对多个url_param hash
server webserver1 192.168.134.10:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.134.20:80 weight 1 check inter 3s fall 3 rise 5

url_param一致性

listen webserver_80
bind 192.168.134.100:80
mode http
balance url_param name,userid #支持对多个url_param hash
hash-type consistent
server webserver1 192.168.134.10:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.134.20:80 weight 1 check inter 3s fall 3 rise 5
(4)hdr
针对用户每个http头部(header)请求中的指定信息做hash,
此处由 name 指定的http首部将会被取出并做hash计算,
然后由服务器总权重取模以后派发至某挑出的服务器,如果无有效值,则会使用默认的轮询调度

hdr取模法

listen webserver_80
bind 192.168.134.100:80
mode http
balance hdr(User-Agent)
server webserver1 192.168.134.10:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.134.20:80 weight 1 check inter 3s fall 3 rise 5

一致性hash 配置

listen webserver_80
bind 192.168.134.100:80
mode http
balance hdr(User-Agent)
hash-type consistent
server webserver1 192.168.134.10:80 weight 1 check inter 3s fall 3 rise 5
server webserver2 192.168.134.20:80 weight 1 check inter 3s fall 3 rise 5
各算法使用场景
first #使用较少
static-rr #做了session共享的web集群
roundrobin
random
leastconn #数据库
source
#基于客户端公网IP的会话保持
Uri--------------->http #缓存服务器,CDN服务商,蓝汛、百度、阿里云、腾讯
url_param--------->http #可以实现session保持
hdr #基于客户端请求报文头部做下一步处理

五、高级功能及配置

1 、基于cookie的会话保持

cookie value:为当前server指定cookie值,实现基于cookie的会话黏性,相对于基于 source 地址hash
调度算法对客户端的粒度更精准,但同时也加大了haproxy负载,目前此模式使用较少, 已经被session共享服务器代替

注意:不支持 tcp mode,使用 http mode

 测试: 

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
 
listen webcluster
        bind            *:80
        option          forwardfor
        mode            http
        #balance        static-rr
        #balance        first
        balance roundrobin
        #balance        leastconn
        #balance        source
        cookie WEBCOOKIE insert nocache indirect
        server  web1    192.168.134.10:80 cookie web1 weight 1 check inter 3s fall 3 rise 5
        server  web2    192.168.134.20:80 cookie web2 weight 1 check inter 3s fall 3 rise 5
 
[root@haproxy ~]# systemctl restart haproxy.service

2 、HAProxy状态页

通过web界面,显示当前HAProxy的运行状态

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
 
 
listen webcluster
        bind            0.0.0.0:8888
        mode            http
        stats   enable
        log global
        stats uri /status
        stats auth zx:zx
        server  web1    192.168.134.10:80 cookie web1 weight 1 check inter 3s fall 3 rise 5
        server  web2    192.168.134.20:80 cookie web2 weight 1 check inter 3s fall 3 rise 5
 
[root@haproxy ~]# systemctl restart haproxy.service
 
浏览器访问:192.168.134.100:8888/status
账号密码:zx/zx

2、IP透传

(1)四层IP透传

未开启四层透传

#未开启透传的四层代理
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
listen webserver_80
bind 172.25.254.100:80
mode tcp
balance roundrobin
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5
...上面内容省略...
#正常的nginx配置
[root@rs1 ~]# vim /etc/nginx/nginx.conf
。。。内容省略。。。
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request"'
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
。。。内容省略。。。
server {
listen 80;
listen [::]:80;
server_name _;
root /usr/share/nginx/html;
。。。内容省略。。。
}
}
#在访问haproxy后查看nginx日志
[root@rs1 ~]# tail -n 3 /var/log/nginx/access.log
192.168.0.10 - - [10/Jul/2024:15:21:00 +0800] "GET / HTTP/1.1"200 18 "-"
"curl/7.29.0" "-"192.168.0.10 - - [10/Jul/2024:15:26:11 +0800] "GET /
HTTP/1.1"200 18 "-" "curl/7.29.0" "-"
在此日志中是无法看到真实访问源地址的
开启四层透传
#nginx 配置:在访问日志中通过变量$proxy_protocol_addr 记录透传过来的客户端IP
[root@rs1 ~]# vim /etc/nginx/nginx.conf
。。。内容省略。。。
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request"'
' "$proxy_protocol_addr"'
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
。。。内容省略。。。
server {
5.3.3 七层IP透传
当haproxy工作在七层的时候,也可以透传客户端真实IP至后端服务器
5.3.3.1 HAProxy配置
在由haproxy发往后端主机的请求报文中添加“X-Forwarded-For"首部,其值为前端客户端的地址;用于
向后端主发送真实的客户端IP
示例:
listen 80 proxy_protocol; #启用此项,将无法直接访问此网站,只能通过四层代理
访问
listen [::]:80;
server_name _;
root /usr/share/nginx/html;
。。。内容省略。。。
}
}
#修改haproxy
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
listen webserver_80
bind 172.25.254.100:80
mode tcp
balance roundrobin
server webserver1 192.168.0.101:80 send-proxy weight 1 check inter 3s fall 3
rise 5
...上面内容省略...
#查看日志内容
[root@rs1 ~]# tail -n 3 /var/log/nginx/access.log
192.168.0.10 - - [10/Jul/2024:15:21:00 +0800] "GET / HTTP/1.1"200 18 "-"
"curl/7.29.0" "-"
192.168.0.10 - - [10/Jul/2024:15:26:11 +0800] "GET / HTTP/1.1"200 18 "-"
"curl/7.29.0" "-"
192.168.0.10 - - [10/Jul/2024:15:41:56 +0800] "GET / HTTP/1.1" "172.25.254.10"200
18 "-" "curl/7.29.0"
(2)七层IP透传

修改haproxy主机的配置文件

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
listen webserver_80
option forwardfor
bind 172.25.254.100:80
mode http
balance roundrobin
server webserver1 192.168.0.101:80 send-proxy weight 1 check inter 3s fall 3
rise 5
server webserver1 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5

realserver的nginx配置文件

log_format  main  '"$proxy_add_x_forwarded_for" - $remote_user [$time_local]
"$request" '
 
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

3、ACL

访问控制列表ACL,Access Control Lists)
是一种基于包过滤的访问控制技术
它可以根据设定的条件对经过服务器传输的数据包进行过滤(条件匹配)即对接收到的报文进行匹配和过
滤,基于请求报文头部中的源地址、源端口、目标地址、目标端口、请求方法、URL、文件后缀等信息内
容进行匹配并执行进一步操作,比如允许其通过或丢弃

域名匹配

haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
frontend testacl
bind :80
mode http
########### ACL settings #######################
acl web_host hdr_dom(host) www.timinglee.org
########### host ###########################
use_backend timinglee_host if web_host
########### default server ###################
default_backend default_webserver
backend timinglee_host
mode http
server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
server web2 192.168.0.102:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
mode http
server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5
...上面内容省略...

测试结果

#在浏览器所在主机中做地址解析
[root@node10 html]# vim /etc/hosts
172.25.254.100 www.timinglee.org
#测试结果
[root@node10 html]# curl www.timinglee.org
RS1 192.168.0.101
[root@node10 html]# curl www.timinglee.org
RS2 server - 192.168.0.102
[root@node10 html]# curl 172.25.254.100
default web server node10

4、haproxy错误页面

(1)在haproxy中自定义错误界面
[root@cll ~]# vim /haproxy/errorpages/503page.http
 
HTTP/1.0 503 Service Unavailable
Cache-Control: no-cache
Connection: close
Content-Type: text/html;charset=UTF-8
 
<html><body><h1>什么动物生气最安静</h1>
大猩猩!!
</body></html>
 
[root@haproxy ~]# vim /etc/haproxy/haproxy.cf
 
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                 3000
 
    errorfile 503 /haproxy/errorpages/503page.http
    
 
[root@haproxy ~]# systemctl restart haproxy.service

记得要关掉realserver的nginx服务,再去验证

5、haproxy四层负载

(1)安装数据库
[root@haproxy ~]#yum install mariadb-server.x86_64 -y
[root@haproxy ~]# systemctl start mariadb.service
[root@haproxy ~]# mysql
#修改数据库id
---------------------------------------------
vim /etc/my.cnf
 
#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]
[mysqld]
server-id=2
 
#
# include all files from the config directory
#
!includedir /etc/my.cnf.d
----------------------------------------------
#192.168.134.10
MariaDB [(none)]> select @@server_id
    -> ;
+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------+
1 row in set (0.000 sec)
#192.168.134.20
MariaDB [(none)]> select @@server_id;
+-------------+
| @@server_id |
+-------------+
|           2 |
+-------------+
1 row in set (0.000 sec)
(2)在haproxy中写配置
frontend mysql_port
        bind :3306
        mode tcp
        use_backend mysql_rs
backend mysql_rs
        mode tcp
        balance leastconn
        server mysql1 192.168.134.10:3306 check
        server mysql2 192.168.134.20:3306 check
(3)realserver
[root@haproxy~]# mysql -e "grant all on *.* to zx@'%' identified by 'zx';"
[root@haproxy ~]# mysql -e "grant all on *.* to zx@'%' identified by 'zx';"
(4)测试
在192.168.134.100中测试:
[root@haproxy ~]# mysql -uzx -pzx -h 192.168.134.10 -e "show variables like 'hostname'"
mysql: [Warning] Using a password on the command line interface can be insecure.
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| hostname      | zx    |
+---------------+-------+
[root@haproxy ~]# mysql -uzx -pzx -h 192.168.134.20 -e "show variables like 'hostname'"
mysql: [Warning] Using a password on the command line interface can be insecure.
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| hostname      | zx    |
+---------------+-------+
 
[root@haproxy ~]# mysql -uzx -pzx -h 192.168.134.10 -e "select @@server_id"
mysql: [Warning] Using a password on the command line interface can be insecure.
+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------+
[root@haproxy ~]# mysql -uzx -pzx -h 192.168.134.20 -e "select @@server_id"
mysql: [Warning] Using a password on the command line interface can be insecure.
+-------------+
| @@server_id |
+-------------+
|           2 |
+-------------+
 
 
在client中访问192.168.183.100
 
C:\Users\cll12>mysql -ucll -pcll -h192.168.183.100 -e "select @@server_id"
mysql: [Warning] Using a password on the command line interface can be insecure.
+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------+
 
C:\Users\cll12>mysql -ucll -pcll -h192.168.183.100 -e "select @@server_id"
mysql: [Warning] Using a password on the command line interface can be insecure.
+-------------+
| @@server_id |
+-------------+
|           2 |
+-------------+

6、HAProxy https 实现

(1)证书制作
制作证书
[root@haproxy certs]# openssl req  -newkey rsa:2048 -nodes  -sha256 -keyout /etc/haproxy/certs/zx.org.key -x509 -days 365 -out 
/etc/haproxy/certs/zx.org.crt
 
[root@haproxy ~]# cd /etc/haproxy/certs/
[root@haproxy certs]# ll
total 12
-rw-r--r-- 1 root root 1350 Jul 20 16:26 zx.org.crt
-rw------- 1 root root 1704 Jul 20 16:26 zx.org.key
-rw-r--r-- 1 root root 3054 Jul 20 16:26 zx.pem
[root@haproxy certs]# ls
zx.org.crt  zx.org.key  zx.pem
 
将证书内容放到一个文件里面---》zx.pem
(2)在haproxy中编写https配置文件
frontend webserver
    bind *:80
    redirect scheme https if !{ ssl_fc }
    mode http
    use_backend webcluster
 
frontend webserver-https
    bind *:443 ssl crt /etc/haproxy/certs/zx.pem
    mode http
    use_backend webcluster
 
backend webcluster
    mode http
    balance roundrobin
    server web1 192.168.134.10:80 check inter 3s fall 3 rise 5
    server web2 192.168.134.20:80 check inter 3s fall 3 rise 5


网站公告

今日签到

点亮在社区的每一天
去签到