haproxy

负载均衡

什么是负载均衡

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

负载均衡的作用

  • Web服务器的动态水平扩展-->对用户无感知

  • 增加业务并发访问及处理能力-->解决单服务器瓶颈问题

  • 节约公网IP地址-->降低IT支出成本 隐藏内部服务器IP-->提高内部服务器安全性

  • 配置简单-->固定格式的配置文件 功能丰富-->支持四层和七层,支持动态下线主机

  • 性能较强-->并发数万甚至数十万

四层负载与七层负载的区别

  1. 分层位置:四层负载均衡在传输层及以下,七层负载均衡在应用层及以下

  2. 性能 :四层负载均衡架构无需解析报文消息内容,在网络吞吐量与处理能力上较高:七层可支持解析应用层报文消息内容,识别URL、Cookie、HTTP header等信息。

  3. 原理:四层负载均衡是基于ip+端口;七层是基于虚拟的网址或主机IP等。

  4. 功能类比:四层负载均衡类似于路由器;七层类似于代理服务器。

  5. 安全性:四层负载均衡无法识别DDoS攻击;七层可防御SYN Cookie/Flood攻击

haproxy的基本部署方法和七层负载均衡实验

环境配置

需要三台虚拟机,一台haproxy,两台webserver

[root@server1 ~] dnf install nginx -y
[root@server1 ~] echo webserver1 - 172.25.254.10 > /usr/share/nginx/html/index.html
[root@server1 ~] systemctl enable nginx.service --now
​
[root@server2 ~] dnf install nginx -y
[root@server2 ~] echo webserver2 - 172.25.254.20 > /usr/share/nginx/html/index.html
[root@server2 ~] systemctl enable nginx.service --now
​
[root@haproxy ~] yum install haproxy -y
haproxy基本配置

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

global:全局配置段

  • 进程及安全配置相关的参数

  • 性能调整相关参数

  • Debug参数

proxies:代理配置段

  • defaults:为frontend,backend,listen提供默认配置

  • frontend:前端,相当于nginx中的server{}

  • backend:后端,相当于nginx中的upstream{}

  • listen:同时拥有前端和后端配置,配置简单,生产推荐使用

[root@haproxy ~] vim /etc/haproxy/haproxy.cfg
#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend webcluster #前端名字唯一,写在defaults后面
    bind *:80 #监听80端口,主机中所有的网络的80端口都开
    mode http #七层(tcp为四层)
    use_backend webcluster-host #使用webcluster-host后端
​
backend webcluster-host
    balance roundrobin #调度规则为rr(roundrobin)
    server web1 172.25.254.10:80 #注意server后面要写名字
    server web2 172.25.254.20:80
#—————————————————————————————————写法二——————————————————————————————
    listen webcluster
    bind *:80
    mode http
    balance roundrobin
    server web1 172.25.254.10:80
    server web2 172.25.254.20:80
    
[root@haproxy ~] cat /var/log/messages #可通过日志查看报错情况
​

测试

#测试后端检测
[root@server1 ~] systemctl stop nginx.service 

定义haproxy日志文件路径
[root@haproxy conf.d] vim /etc/rsyslog.conf
# for parameters see http://www.rsyslog.com/doc/imudp.html
module(load="imudp") # needs to be done just once #开启
input(type="imudp" port="514")
​
# Save boot messages also to boot.log
local7.*                                                /var/log/boot.log
#增加文件路径

global配置

global参数:

global
    log         127.0.0.1 local2 #设置日志级别是2,日志记录在本机
    chroot      /var/lib/haproxy #设定haproxy的运行目录为/var/lib/haproxy
    pidfile     /var/run/haproxy.pid #pid文件
    maxconn     4000 #最大连接数为4000
    user        haproxy #运行用户
    group       haproxy #运行组
    daemon #后台运行
 # turn on stats unix socket
    stats socket /var/lib/haproxy/stats #状态接口
​
    # utilize system-wide crypto-policies
    ssl-default-bind-ciphers PROFILE=SYSTEM 这支持ssl的加密认证
    ssl-default-server-ciphers PROFILE=SYSTEM
    nbproc 2 #设置进程数为2
    cpu-map 1 0 #进程和cpu核心绑定,防止产生cpu飘逸  1表示第一个进程,0表示第1个cpu核心
    cpu-map 2 1 #2表示为第二个进程,1表示第二个cpu核心
    nbthread 2 #设置线程数为2(不能与设置多进程同时使用)
[root@haproxy ~] pstree -p | grep haproxy #查看进程
           |-haproxy(2011)-+-haproxy(2014)
           |               `-haproxy(2015)
[root@haproxy ~] cat /proc/2015/status | grep Thread #查看2015进程中的线程数量
Threads:    1
​
proxies配置

proxies参数

defaults
    mode                    http
    log                     global #日志沿用global中的log设定
    option                  httplog #记录http的日志
    option                  dontlognull #记录空连接的日志
    option http-server-close #等待客户端完成http请求,默认10s后关闭
    option forwardfor       except 127.0.0.0/8 #日志透传
    option                  redispatch #当server id对应服务器挂掉后强制定向到其他服务器
    retries                 3 #连接后端服务器失败次数
    timeout http-request    10000s #等待客户端请求完全被接收和处理的最长时间
    timeout queue           1m #一微秒
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s #http保持会话
    timeout check           10s #后端服务器的健康检查的超时时间
    maxconn                 3000 #haproxy能承受的最大并发量
​
[root@haproxy ~] vim /etc/haproxy/haproxy.cfg
listen webcluster
    bind *:80
    mode http
    balance static-rr
   # balance roundrobin
   # redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
    #访问10时,首先进行check检测,每隔两秒检测一次,三次没连接上宣告下线,检测成功5次后下线,权重为2
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
    server web_sorry 172.25.254.100:8080 backup
    #设定一个sorry server
​

sorryserver设置:

[root@haproxy ~] yum install httpd -y
[root@haproxy ~] yum install httpd -y^C
[root@haproxy ~] vim /var/www/html/index.html 
[root@haproxy ~] cat /var/www/html/index.html 
sorry, it is time to go to bed 
[root@haproxy ~] vim /etc/httpd/conf/httpd.conf #修改http的端口(sorryserver的端口)
#Listen 12.34.56.78:80
Listen 8080
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
"/etc/httpd/conf/httpd.conf" 358L, 12007B  
[root@haproxy ~] systemctl restart httpd
[root@haproxy ~] vim /etc/haproxy/haproxy.cfg 
listen webcluster
    bind *:80
    mode http
    balance static-rr
   # balance roundrobin
   # redirect prefix http://www.baidu.com/
   # 将请求临时重定向到其他url,只适用于http模式
    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2 disabled
    #disabled下线指定realserver
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1 disabled
    server web_sorry 172.25.254.100:8080 backup #不参与调度,仅当web1,2都挂了的时候才访问
haproxy热更新方法

目的:修改haproxy工作方式以后不需要重启,不会影响其他集群的状态,且可以编入脚本中自动执行

[root@haproxy ~] vim /etc/haproxy/haproxy.cfg
    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats mode 600 level admin #记录haprxy状态,默认只能查看
    #mode 600:修改文件权限为600(a+r,w), level admin 管理员 

使用方法

[root@haproxy ~] dnf install socat -y #现在socat工具,能够动态的调整haproxy里面的参数
[root@haproxy ~] echo "help" | socat stdio /var/lib/haproxy/stats #查看socat工具帮助

常规实例(单进程)

[root@haproxy ~] echo "show info" | socat stdio /var/lib/haproxy/stats #显示haproxy状态
[root@haproxy ~] echo "show servers state" | socat stdio /var/lib/haproxy/stats #显示server状态
[root@haproxy ~] echo get weight webcluster/web1 | socat stdio /var/lib/haproxy/stats 
2 (initial 2) #查看webcluster下的web1的权重,2表示当前权重为2,initia 2表示编写的权重为2,以当前权重为准
[root@haproxy ~] echo “set weight webcluster/web1 1” | socat stdio /var/lib/haproxy/stats #修改权限为1
[root@haproxy ~] echo "disable server webcluster/web1" | socat stdio /var/lib/haproxy/stats #将webcluster下的web1下线
[root@haproxy ~] echo "enable server webcluster/web1" | socat stdio /var/lib/haproxy/stats #将webcluster下的web1上线

处理多进程的方法

[root@haproxy ~] vim /etc/haproxy/haproxy.cfg
    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats1 mode 600 level admin process 1#指定处理进程1
    #记录haprxy状态,默认只能查看
    stats socket /var/lib/haproxy/stats2 mode 600 level admin process 2#指定处理进程2
    #mode 600:修改文件权限为600(a+r,w), level admin 管理员 
    .。。。。
     nbproc 2
    cpu-map 1 0
    cpu-map 2 1 #开启多进程

haproxy的算法

静态算法

按照事先定义好的规则轮询公平调度,不关心后端服务器的当前负载,连接数和响应速度等,且无法实时修改权重(只能为0或1,不支持其他值),只能靠重启haproxy生效

static-rr:基于权重的轮询调度
  • 不支持运行时利用socat进行权重的动态调整(只支持0和1)

  • 不支持端服务器慢启动(服务刚启动时缓慢的给流量)

  • 其后端主机数量没有限制,相当于lvs中的wrr

listen webcluster
    bind *:80
    mode http
    balance static-rr #设置static-rr
   # balance roundrobin
   # redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
    server web_sorry 172.25.254.100:8080 backup
​
[root@haproxy ~] echo "set weight webcluster/web1 1" | socat stdio /var/lib/haproxy/stats 
Backend is using a static LB algorithm and only accepts weights '0%' and '100%'.
#不能修改

效果展示

[root@servera ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
​
first
  • 根据服务器在列表的位置,从上往下调度,只有第一个满了才调度到下一台

  • 会忽略服务器的权重设置

  • 不支持socat进行动态修改权重

listen webcluster
    bind *:80
    mode http
    balance first
   # balance static-rr 
   # balance roundrobin
   # redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 1 check inter 2 fall 3 rise 5 weight 2 #最大连接数改为1
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
    server web_sorry 172.25.254.100:8080 backup
​

效果展示

[root@servera ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20#在多台虚拟机上做死循环,模拟web1服务器满了的情况,所以出现20
webserver1 - 172.25.254.10
​

动态算法

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

roundrobin
  • 基于权重的轮询动态调度算法

  • 支持权重的运行时调整,不同于lvs中的rr轮询的一点是支持慢启动

  • 后端支持4095个real server

  • 支持对real server权重动态调整,将流量打到权重高且负载小的主机,优先选择负载小

  • 使用广泛,为默认算法

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
    balance roundrobin
   # redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 1 check inter 2 fall 3 rise 5 weight 2
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
    server web_sorry 172.25.254.100:8080 backup
​
[root@haproxy ~]# echo "set weight webcluster/web1 1" | socat stdio /var/lib/haproxy/stats
​
[root@haproxy ~]# echo "get weight webcluster/web1" | socat stdio /var/lib/haproxy/stats
1 (initial 2)

效果展示

[root@servera ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
#这样显示的原因为开启了多台虚拟机上做死循环,roundrobin选择负载小且权重高的主机,优先选择负载小
leastconn

加权最少链接的动态

支持权重的运行时调整和慢启动,根据当前连接最少的后端服务器而不是权重进行优先调度

比较适合长连接的场景使用,比如MySQL

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
   # balance roundrobin
     balance leastconn
   # redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 1 check inter 2 fall 3 rise 5 weight 2
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
    server web_sorry 172.25.254.100:8080 backup
​

其他算法

其他算法既可以作为静态,也可以通过选项作为动态,通过在haproxy.cfg中设置hash-type consistent改为动态

source

源地址hash,基于用户源地址hash并将请求转发到后端服务器,后续同一个源地址请求将被转发至同一个web服务器中。默认为静态方式,可以通过hash-type支持选项更改,一般是在不插入Cookie的TCP模式下使用,也可以拒绝会话cookie的客户提供最好的会话粘性,有两种转发客户端请求到后端服务器选取计算方法,分别为取模法和hashi一致法

map-base取模法

对source地址进行hash计算,再基于服务器总权重的取模决定此请求转发至对应的后端服务器。此方法为静态,不支持在线调整权重,不支持慢启动,是hash-type指定的默认算法

缺点:服务器总权重发生变化时,如有服务器上线或下线,都会导致调度结果整体改变,导致会话丢失

hash一致性

当服务器总权重发生变化时,对调度结果的影响是局部的,不会引起大的变动。此方法是动态的,支持haproxy的热处理,支持慢启动

算法:

1、后端服务器哈希环点keyA=hash(后端服务器虚拟ip)%(2^32),得到的值在[0---2^32-1]之间
2、客户机哈希环点key1=hash(client_ip)%(2^32) 得到的值在[0---2^32-1]之间
3、将keyA和key1都放在hash环上,将用户请求调度到离key1最近的keyA对应的后端服务器,以顺时针在hash环上找

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
   # balance roundrobin
   # balance leastconn
   # redirect prefix http://www.baidu.com/
   # cookie webcookie insert nocache indirect
    balance source
    hash-type consistent #加上为动态,使用hash一致性,不加则为静态,使用source
    server web1 172.25.254.10:80 send-proxy check inter 2 fall 3 rise 5 weight 2
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
    server web_sorry 172.25.254.100:8080 backup
​
uri

uri:资源在互联网中的唯一标识符,url:资源在服务器中的真实位置

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

  • 适用于后端是缓存服务器场景

  • 默认是静态算法,也可以使用hash-type指定map-based和consistent来定义使用取模还是hash一致性

<scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<frag>
#<scheme>协议名称,<user>:<password>用户和密码(web中不写),<params>:指令<query>:指令指定的某一字段,<frag>:快速索引文章中的某一片段
左半部分:/<path>;<params>
整个uri:/<path>;<params>?<query>#<frag>
listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
   # balance roundrobin
   # balance leastconn
     balance uri
   # balance source
    hash-type consistent
   # redirect prefix http://www.baidu.com/
​
    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
   # server web_sorry 172.25.254.100:8080 backup
​
[root@server2 ~] echo 172.25.254.20 - index1.html > /usr/share/nginx/html/index1.html
[root@server2 ~] echo 172.25.254.20 - index2.html > /usr/share/nginx/html/index2.html
[root@server2 ~] echo 172.25.254.20 - index3.html > /usr/share/nginx/html/index3.html
​
[root@server1 ~] echo 172.25.254.10 - index1.html > /usr/share/nginx/html/index1.html
[root@server1 ~] echo 172.25.254.10 - index2.html > /usr/share/nginx/html/index2.html
[root@server1 ~] echo 172.25.254.10 - index3.html > /usr/share/nginx/html/index3.html
​

效果展示

[root@servera ~] curl 172.25.254.100/index1.html
172.25.254.10 - index1.html
[root@servera ~] curl 172.25.254.100/index2.html
172.25.254.20 - index2.html
[root@servera ~] curl 172.25.254.100/index3.html
172.25.254.10 - index3.html
[root@servera ~] curl 172.25.254.100/index3.html
172.25.254.10 - index3.html #uri不变,访问的路径或地址也不变
​
url-param

对用户请求的url中的params部分中的一个参数key对应的value值进行hash计算,常用于追踪用户,确保来自同一个用户的请求始终发往同一个real server,如果没key按rr算法执行

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
   # balance roundrobin
   # balance leastconn
   # balance uri
    balance url_param name,userid #关键字为name,userid
   # balance source
    hash-type consistent
   # redirect prefix http://www.baidu.com/
​
    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
   # server web_sorry 172.25.254.100:8080 backup
​
[root@servera ~]# curl 172.25.254.100/index.html?name=lee
webserver1 - 172.25.254.10
[root@servera ~]# curl 172.25.254.100/index.html?name=lee
webserver1 - 172.25.254.10
[root@servera ~]# curl 172.25.254.100/index.html?name=lee
webserver1 - 172.25.254.10
[root@servera ~]# curl 172.25.254.100/index.html?name=test
webserver2 - 172.25.254.20
[root@servera ~]# curl 172.25.254.100/index.html?name=test
webserver2 - 172.25.254.20
#搜索为同一name,则被调度到同一服务器上
hdr

针对用户每个http头部(header)请求中的指定信息做hash,由name指定的http头部将会被取出并做hash,然后由服务器总权重取模之后派发至某跳出的服务器,如果无有效值则会使用默认的轮询调度,适用于不同的浏览器访问不同的主机

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
   # balance roundrobin
   # balance leastconn
   # balance uri
   # balance url_param name,userid
    balance hdr(User-Agent) #User-Agent:浏览器
   # balance source
    hash-type consistent
   # redirect prefix http://www.baidu.com/
​
    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
   # server web_sorry 172.25.254.100:8080 backup
​

效果演示

[root@servera ~]# curl -vA "360" 172.25.254.100
*   Trying 172.25.254.100:80...
* Connected to 172.25.254.100 (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: 360 #假设访问的360浏览器
。。。。。。
webserver2 - 172.25.254.20 #到20
* Connection #0 to host 172.25.254.100 left intact
[root@servera ~]# curl -vA "firefox" 172.25.254.100
*   Trying 172.25.254.100:80...
* Connected to 172.25.254.100 (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: firefox #假设访问firefox浏览器
。。。。。。
webserver1 - 172.25.254.10 #到10
* Connection #0 to host 172.25.254.100 left intact
​

算法总结

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

各算法使用场景

first #使用较少
static-rr #做了session共享的web集群
roundrobin
leastconn #数据库
source
#基于客户端公网IP的会话保持
Uri--------------->http #缓存服务器,CDN服务商,蓝汛、百度、阿里云、腾讯
url_param--------->http #可以实现session保持
hdr #基于客户端请求报文头部做下一步处理

haproxy状态页

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

stats enable #基于默认的参数启用stats page
stats hide-version #将状态页中haproxy版本隐藏
stats refresh <delay> #设定自动刷新时间间隔,默认不自动刷新
stats uri <prefix> #自定义stats page uri,默认值:/haproxy?stats
stats auth <user>:<passwd> #认证时的账号和密码,可定义多个用户,每行指定一个用户
#默认:不用认证
stats admin { if | unless } <cond> #启用stats page中的管理功能,为了安全性一般不启动
#---------------------------------------------------------------------
listen stats
    mode http #模式为http
    bind *:1234 #监听端口为1234
    stats enable #打开状态页功能
    stats uri /status #自定义status,访问时应写:172.25.254.100:1234/status
    stats auth lee:lee #验证时账号密码都为lee
    
#---------------------------------------------------------------------
​

效果展示

高级功能及配置

基于cookie的会话保持

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

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
    balance roundrobin
   # balance leastconn
   # redirect prefix http://www.baidu.com/
    cookie webcookie insert nocache indirect
    #cookie的名字为webcookie,insert:插入新的cookie,nocache:如果有缓存服务器则不缓存cookie,indirect
    server web1 172.25.254.10:80 cookie lee1 check inter 2 fall 3 rise 5 weight 2
    #当被调度到10rs上时,会发送一个cookie=lee1并进行缓存,下次访问时验证cookie的值,为lee1就继续调度到10的rs上
    server web2 172.25.254.20:80 cookie lee2 check inter 2 fall 3 rise 5 weight 1
    server web_sorry 172.25.254.100:8080 backup
​

效果展示

IP透传

web服务器中需要记录客户端的真实IP地址,用于做访问统计、安全防护、行为分析、区域排行等场景。

七层ip透传
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8 #关闭则不进行ip透传,如果是回环接口访问也不做透传
。。。。。。
listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
    balance roundrobin
   # balance leastconn
   # balance uri
   # balance url_param name,userid
   # balance hdr(User-Agent)
   # balance source
   # hash-type consistent
   # redirect prefix http://www.baidu.com/
   # cookie webcookie insert nocache indirect
    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
   # server web_sorry 172.25.254.100:8080 backup
​
[root@servera ~] curl 172.25.254.100
webserver2 - 172.25.254.20
[root@server2 ~] cat /var/log/nginx/access.log 
172.25.254.100 - - [11/Aug/2024:17:13:30 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "172.25.254.101" #打开forwordfor可以看见访问的真实主机地址

注意:如果为apache默认情况下也看不到真实主机地址

[root@server1 ~] systemctl disable nginx.service 
Removed "/etc/systemd/system/multi-user.target.wants/nginx.service".
[root@server1 ~] systemctl stop nginx.service #关闭nginx
[root@server1 ~] echo "webserver1 - 172.25.254.10(apache)" > /var/www/html/index.html
[root@server1 ~] systemctl start httpd打开apache
[root@servera ~] curl 172.25.254.100
webserver2 - 172.25.254.20
[root@servera ~] curl 172.25.254.100
webserver1 - 172.25.254.10(apache)
[root@servera ~] curl 172.25.254.100
[root@server1 ~] cat /etc/httpd/logs/access_log 
172.25.254.100 - - [11/Aug/2024:17:20:51 +0800] "GET / HTTP/1.1" 200 35 "-" "curl/7.76.1"
172.25.254.100 - - [11/Aug/2024:17:20:52 +0800] "GET / HTTP/1.1" 200 35 "-" "curl/7.76.1" #apache默认情况下看不到rs
[root@server1 ~] vim /etc/httpd/conf/httpd.conf
LogLevel warn
​
<IfModule log_config_module>
    LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined #combined:在apache中表示为混合型日志,包含各种日志
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
[root@server1 ~]# systemctl restart httpd
[root@servera ~] curl 172.25.254.100
webserver2 - 172.25.254.20
[root@servera ~] curl 172.25.254.100
webserver1 - 172.25.254.10(apache)
​
[root@server1 ~] cat /etc/httpd/logs/access_log 
172.25.254.100 - - [11/Aug/2024:17:20:51 +0800] "GET / HTTP/1.1" 200 35 "-" "curl/7.76.1"
172.25.254.100 - - [11/Aug/2024:17:20:52 +0800] "GET / HTTP/1.1" 200 35 "-" "curl/7.76.1"
172.25.254.101 172.25.254.100 - - [11/Aug/2024:17:27:17 +0800] "GET / HTTP/1.1" 200 35 "-" "curl/7.76.1" #能看到rs101
四层ip透传

apache在四层无法做到透传

listen webcluster
    bind *:80
    mode tcp #tcp为四层
   # balance first
   # balance static-rr 
    balance roundrobin
   # balance leastconn
   # balance uri
   # balance url_param name,userid
   # balance hdr(User-Agent)
   # balance source
   # hash-type consistent
   # redirect prefix http://www.baidu.com/
   # cookie webcookie insert nocache indirect
    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
   # server web_sorry 172.25.254.100:8080 backup
​
[root@servera ~] curl 172.25.254.100
webserver1 - 172.25.254.10(apache)
[root@servera ~] curl 172.25.254.100
webserver2 - 172.25.254.20
​
[root@server1 ~] cat /etc/httpd/logs/access_log 
172.25.254.100 - - [11/Aug/2024:17:20:51 +0800] "GET / HTTP/1.1" 200 35 "-" "curl/7.76.1"
172.25.254.100 - - [11/Aug/2024:17:20:52 +0800] "GET / HTTP/1.1" 200 35 "-" "curl/7.76.1"
172.25.254.101 172.25.254.100 - - [11/Aug/2024:17:27:17 +0800] "GET / HTTP/1.1" 200 35 "-" "curl/7.76.1"
- 172.25.254.100 - - [11/Aug/2024:17:30:58 +0800] "GET / HTTP/1.1" 200 35 "-" "curl/7.76.1" #改为四层后,做好配置的apache无法看到rs
​
[root@server2 ~] cat /var/log/nginx/access.log 
172.25.254.100 - - [11/Aug/2024:17:32:39 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-" #改为四层后,nginx也无法看到rs
​

更改设定

listen webcluster
    bind *:80
    mode tcp
   # balance first
   # balance static-rr 
    balance roundrobin
   # balance leastconn
   # balance uri
   # balance url_param name,userid
   # balance hdr(User-Agent)
   # balance source
   # hash-type consistent
   # redirect prefix http://www.baidu.com/
   # cookie webcookie insert nocache indirect
    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1 #send-proxy:表示做的代理,apache默认支持代理
    server web2 172.25.254.20:80 send-proxy check inter 2 fall 3 rise 5 weight 1
   # server web_sorry 172.25.254.100:8080 backup
​
[root@server2 ~] vim /etc/nginx/nginx.conf
​
   # for more information.
    include /etc/nginx/conf.d/*.conf;
​
    server {
        listen       80 proxy_protocol; #增加proxy_protocol,如改为七层这个参数一定要去掉
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;
[root@server2 ~]# systemctl restart nginx.service
​

效果展示

[root@servera ~]# curl 172.25.254.100
webserver1 - 172.25.254.10(apache)
[root@servera ~] curl 172.25.254.100
webserver2 - 172.25.254.20 #20能过来是因为20上修改了nginx的配置,此时10上使用的为apache
​
[root@server2 ~] tail /var/log/nginx/access.log
172.25.254.100 - - [11/Aug/2024:17:41:09 +0800] "PROXY TCP4 172.25.254.100 172.25.254.20 38562 80" 400 0 "-" "-" "-"
172.25.254.100 - - [11/Aug/2024:17:41:28 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"仍然不能看见rs

继续添加参数

[root@server2 ~]# vim /etc/nginx/nginx.conf
​
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      ' "$proxy_protocol_addr"' #在日志的显示内容在添加地址
                      '"$http_user_agent" "$http_x_forwarded_for"';
[root@server2 ~]# systemctl restart nginx.service
​

效果展示

[root@servera ~]# curl 172.25.254.100
webserver1 - 172.25.254.10(apache)
[root@servera ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
​
[root@server2 ~] tail /var/log/nginx/access.log
172.25.254.100 - - [11/Aug/2024:17:41:28 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-" #此为添加$proxy_protocol_addr之前的日志
172.25.254.100 - - [11/Aug/2024:17:48:27 +0800] "GET / HTTP/1.1" 200 27 "-"  "172.25.254.101""curl/7.76.1" "-" #此为添加$proxy_protocol_addr之后的日志,能看到rs
​

ACL

是一种基于包过滤的访问控制技术

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

acl匹配规范
hdr
[root@haproxy haproxy]# vim haproxy.cfg
frontend webcluster
    bind *:80
    mode http
    acl test hdr_dom(host) -i www.jisoo.org 
    # -i:忽略大小写, hdr_dom(host):与host进行匹配
    #acl test hdr_end(host) -i .org #hdr_end(host):与结尾为.org的host进行匹配
    #acl test hdr_beg(host) -i  bbs #hdr_beg(host):与开头为bbs的host进行匹配
    use_backend webcluster-host if test 
    #如果符合test的设定,就访问webcluster-host设定的10
    default_backend default-host
    #如果不符合就访问default-host设定的20,默认
​
backend webcluster-host
    mode http
    server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
​
backend default-host
    mode http
    server web2 172.25.254.20:80 check inter 2 fall 2 rise 5
[root@haproxy haproxy]# systemctl restart haproxy.service

效果展示

在虚拟机中添加解析
[root@servera ~]# vim /etc/hosts
  127.0.0.1   localhost localhost.localdomain localhost4      localhost4.localdomain4
  ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
  172.25.254.100 www.jisoo.org                         
[root@servera ~]# curl www.jisoo.org
webserver1 - 172.25.254.10(apache)
[root@servera ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
​
base

#返回第一个主机头和请求的路径部分的连接,该请求从主机名开始,并在问号之前结束,对虚拟主机有用

<scheme>://<user>:<password>@#<host>:<port>/<path>;<params>#?<query>#<frag> <scheme>://<user>:<password>@#<host>:<port>/<path>;<params>为base

frontend webcluster
    bind *:80
    mode http
    #acl test hdr_dom(host) -i www.jisoo.org
    #acl test hdr_end(host) -i .org
    acl test base_sub -m sub bbs
    #表示与在名字中包含bbs的匹配
    #acl test base_reg -i bbs/$ #匹配名字中以bbs结尾
    use_backend webcluster-host if test
    default_backend default-host
​
backend webcluster-host
    mode http
    server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
​
backend default-host
    mode http
    server web2 172.25.254.20:80 check inter 2 fall 2 rise 5
    
[root@server1 ~] mkdir /var/www/html/bbs -p
[root@server1 ~] echo 172.25.254.10 bbs > /var/www/html/bbs/index.html
​

效果展示

[root@servera ~] vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
172.25.254.100 www.jisoo.org bbs.jisoo.org www.jisoobbs.org 
[root@servera ~] curl www.jisoobbs.org
webserver1 - 172.25.254.10(apache)
[root@servera ~] curl bbs.jisoo.org
webserver1 - 172.25.254.10(apache)
[root@servera ~] curl www.jisoo.org
webserver2 - 172.25.254.20
[root@servera ~] curl www.jisoo.org
webserver2 - 172.25.254.20
[root@servera ~] curl www.jisoo.org/bbs/ #尽管地址中没有带有bbs,但访问带有bbs的文件即路径包含bbs还是能访问到10
172.25.254.10 bbs
​
path

#提取请求的URL路径,该路径从第一个斜杠开始,并在问号之前结束(无主机部分)

<scheme>://<user>:<password>@<host>:<port>#/<path>;<params>#?<query>#<frag> <path>;<params>为path

base中包含path,因为base表示的更多,包括path表示的

frontend webcluster
    bind *:80
    mode http
    #acl test hdr_dom(host) -i www.jisoo.org
    #acl test hdr_end(host) -i .org
    #acl test base_sub -m sub bbs
    acl test path_sub -m sub bbs
    use_backend webcluster-host if test
    default_backend default-host
​
backend webcluster-host
    mode http
    server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
​
backend default-host
    mode http
    server web2 172.25.254.20:80 check inter 2 fall 2 rise 5
​

效果展示:

[root@servera ~] curl www.jisoo.org
webserver2 - 172.25.254.20
[root@servera ~] curl bbs.jisoo.org 
#尽管包含了bbs但不在path包含的范围内,所以显示20
webserver2 - 172.25.254.20
[root@servera ~] curl bbs.jisoo.org/bbs/
172.25.254.10 bbs
[root@servera ~] curl www.jisoo.org/bbs/
#尽管没有bbs但最终是以bbs结尾,/后面为path包含的范围,所以可以显示10
172.25.254.10 bbs
​
acl匹配模式

-i 不区分大小写

-m 使用指定的正则表达式匹配方法

-n 不做DNS解析

-u 禁止acl重名,否则多个同名ACL匹配或关系

acl具体操作符

整数比较: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进行匹配

acl操作对象
  • - Boolean #布尔值

  • - integer or integer range #整数或整数范围,比如用于匹配端口范围

  • - IP address / network #IP地址或IP范围, 192.168.0.1 ,192.168.0.1/24

  • - string--> www.timinglee.org

    • exact #精确比较

    • substring #子串

    • suffix #后缀比较

    • prefix #前缀比较

    • subdir #路径, /wp-includes/js/jquery/jquery.js

    • domain #域名,www.timinglee.org

  • - regular expression #正则表达式

  • - hex block #16进制

acl逻辑处理

与:隐式(默认)使用

或:使用“or" 或 “||"表示

否定:使用 "!" 表示

利用acl做动静分离等访问控制
基于域名的访问
frontend webcluster
    bind *:80
    mode http
    acl domain hdr_dom(host) -i www.jisoo.org 
    use_backend webcluster-host if domain
    default_backend default-host
​
backend webcluster-host
    mode http
    server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
​
backend default-host
    mode http
    server web2 172.25.254.20:80 check inter 2 fall 2 rise 5
​
[root@servera ~] curl www.jisoo.org
webserver1 - 172.25.254.10(apache)
[root@servera ~] curl www.jisoo.org/bbs/
172.25.254.10 bbs
[root@servera ~] curl bbs.jisoo.org
webserver2 - 172.25.254.20
​
基于源ip或子网调度的访问
frontend webcluster
    bind *:80
    mode http
   # acl domain hdr_dom(host) -i www.jisoo.org
    acl ctrl_ip src 172.25.254.101 172.25.254.20
    use_backend webcluster-host if ctrl_ip
   # http-request deny if ctrl_ip #表示只拒绝以上ip地址访问
    default_backend default-host
​
backend webcluster-host
    mode http
    server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
​
backend default-host
    mode http
    server web2 172.25.254.20:80 check inter 2 fall 2 rise 5
[root@server2 ~] curl 172.25.254.100
webserver1 - 172.25.254.10(apache)
[root@servera ~] curl 172.25.254.100
webserver1 - 172.25.254.10(apache)
acl匹配浏览器类型
frontend webcluster
    bind *:80
    mode http
   # acl domain hdr_dom(host) -i www.jisoo.org
   # acl ctrl_ip src 172.25.254.101 172.25.254.20
    acl badwebrowers hdr_sub(User-Agent) -i curl wget #表示拒绝以上浏览器访问
   # use_backend webcluster-host if ctrl_ip
    http-request deny if badwebrowers
    default_backend default-host
​
backend webcluster-host
    mode http
    server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
​
backend default-host
    mode http
    server web2 172.25.254.20:80 check inter 2 fall 2 rise 5
​
[root@servera ~] curl 172.25.254.100 #使用curl被拒绝
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
​

使用谷歌浏览器成功访问

acl基于后缀名进行动静分离

1.下载php并写好php测试页

[root@server1 ~]# dnf install php -y
[root@server1 ~]# systemctl restart httpd.service 
[root@server1 ~]# vim /var/www/html/index.php
[root@server1 ~]# cat /var/www/html/index.php 
<?php
    phpinfo();
?>
​

2.修改acl

frontend webcluster
    bind *:80
    mode http
    acl static path_end -i .html .jpg .png .css .js #将静态设置为匹配以上述字符结尾
    acl php    path_end -i .php #将动态设置为匹配以php结尾
   # use_backend webcluster-host if ctrl_ip
    use_backend webcluster-host if php #只判断动态,其余的默认
    default_backend default-host
​
backend webcluster-host
    mode http
    server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
​
backend default-host
    mode http
    server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

效果演示

acl基于访问路径的动静分离

1.确保acl中路径真实存在

[root@server2 ~] mkdir /usr/share/nginx/html/static -p
[root@server2 ~] echo static - 172.25.254.20 > /usr/share/nginx/html/static/index.html
[root@server2 ~] curl 172.25.254.20/static/
static - 172.25.254.20
[root@server1 ~] mkdir /var/www/html/php
[root@server1 ~] cp /var/www/html/index.php  /var/www/html/php/
frontend webcluster
    bind *:80
    mode http
    acl static path_sub -m sub static #匹配带有static字段的
    acl php    path_sub -m sub php #匹配带有php字段的
   # use_backend webcluster-host if ctrl_ip
    use_backend webcluster-host if php
    default_backend default-host
​
backend webcluster-host
    mode http
    server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
​
backend default-host
    mode http
    server web2 172.25.254.20:80 check inter 2 fall 2 rise 5
​

效果展示

haproxy自定义错误界面

对指定的报错进行重定向,进行优雅的显示错误页面

使用errorfile和errorloc指令的两种方法,可以实现自定义各种错误页面,以修改503界面为例

errorfile

[root@server1 ~] systemctl stop httpd.service
[root@server2 ~] systemctl stop nginx.service 

当两台主机都关闭服务时,访问100主机显示

1.找到错误页面的地址:

[root@haproxy haproxy] rpm -ql haproxy | grep http
/usr/share/doc/haproxy/design-thoughts/http2.txt
/usr/share/doc/haproxy/design-thoughts/http_load_time.url
/usr/share/doc/haproxy/internals/http-cookies.txt
/usr/share/doc/haproxy/internals/http-docs.txt
/usr/share/doc/haproxy/internals/http-parsing.txt
/usr/share/doc/haproxy/option-http_proxy.cfg
/usr/share/haproxy/400.http
/usr/share/haproxy/403.http
/usr/share/haproxy/408.http
/usr/share/haproxy/500.http
/usr/share/haproxy/502.http
/usr/share/haproxy/503.http
/usr/share/haproxy/504.http
#各错误地址都显示在这里

2.自定义错误界面

[root@haproxy haproxy] mkdir /etc/haproxy/errorpage -p
[root@haproxy haproxy] cp /usr/share/haproxy/503.http /etc/haproxy/errorpage/503.http
cp: overwrite '/etc/haproxy/errorpage/503.http'? y
[root@haproxy haproxy] vim /etc/haproxy/errorpage/503.http 
[root@haproxy haproxy] cat /etc/haproxy/errorpage/503.http 
HTTP/1.0 503 Service Unavailable
Cache-Control: no-cache
Connection: close
Content-Type: text/html
​
<html><body><h1>出现错误</h1>
请检查
</body></html>

3.指定新的503文件

[root@haproxy haproxy] vim /etc/haproxy/haproxy.cfg 
 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 /etc/haproxy/errorpage/503.http
​
    #添加在全局的global中,不添加的时候为默认位置的503
[root@haproxy haproxy] systemctl restart haproxy.service

errorloc

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 /etc/haproxy/errorpage/503.http
    errorloc 503 http://www.baidu.com #当本应该显示503界面时不显示503界面,而是直接跳转到百度
​

haproxy的四层负载实验

针对除HTTP以外的TCP协议应用服务访问的应用场景,如MySQL,Redis,Memcache,RabbitMQ

1.安装并配置数据库

[root@server1 ~] dnf install mariadb-server -y
[root@server2 ~] dnf install mariadb-server -y
[root@server1 ~] vim /etc/my.cnf.d/mariadb-server.cnf
[mysqld]
server-id=1 #设置serverid,便于区分
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mariadb/mariadb.log
pid-file=/run/mariadb/mariadb.pid
​
[root@server2 ~] vim /etc/my.cnf.d/mariadb-server.cnf
[mysqld]
server-id=2
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mariadb/mariadb.log
pid-file=/run/mariadb/mariadb.pid
​
[root@server1 ~] mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.16-MariaDB MariaDB Server
​
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
​
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
​
MariaDB [(none)]> select @@server_id;
+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------+
1 row in set (0.000 sec)
​
MariaDB [(none)]> 
​
[root@server2 ~] mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.16-MariaDB MariaDB Server
​
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
​
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
​
MariaDB [(none)]> select @@server_id;
+-------------+
| @@server_id |
+-------------+
|           2 |
+-------------+
1 row in set (0.000 sec)
​
[root@haproxy haproxy] yum install mariadb -y 安装mariadb,使用里面的MySQL命令

2.数据库增加远程登录的用户,两台server上都做

MariaDB [(none)]> create user lee@'%' identified by 'lee';
#创建一个用户lee可以在除了本机以外的任何远程客户端登录,建立密码为lee
Query OK, 0 rows affected (0.001 sec)
MariaDB [(none)]> grant all on *.* to lee@'%';
# 将所有库的所有表都给lee

尝试访问

[root@haproxy haproxy]# mysql -ulee -plee -h 172.25.254.10
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 5
Server version: 10.5.16-MariaDB MariaDB Server
​
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
​
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
​
MariaDB [(none)]> 
​

3.配置haproxy

[root@haproxy haproxy] vim /etc/haproxy/haproxy.cfg
listen dbserver
    bind *:3306
    mode tcp
    balance roundrobin
    server db1 172.25.254.10:3306 check inter 2 fall 2 rise 5
    server db2 172.25.254.20:3306 check inter 2 fall 2 rise 5
[root@haproxy haproxy] systemctl restart haproxy.service

4.测试结果

[root@haproxy haproxy] mysql -ulee -plee -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 6
Server version: 10.5.16-MariaDB MariaDB Server
​
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
​
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
​
MariaDB [(none)]> select @@server_id
    -> ;
+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------+
1 row in set (0.001 sec)
MariaDB [(none)]> quit
[root@haproxy haproxy] mysql -ulee -plee -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4
Server version: 10.5.16-MariaDB MariaDB Server
​
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
​
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
​
MariaDB [(none)]> select @@server_id;
+-------------+
| @@server_id |
+-------------+
|           2 |
+-------------+
1 row in set (0.001 sec)
​

haproxy的加密访问

1.创建公钥私钥

[root@haproxy haproxy] mkdir /etc/haproxy/certs #创建存放证书和密钥的目录
[root@haproxy haproxy] openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/timinglee.org.key -x509 -days 356 -out /etc/haproxy/certs/timinglee.org.crt 
#nodes:开启时不需要输密码 -sha256:加密方式  -x509:证书格式 -day 365:证书有效期
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:Shannxi
Locality Name (eg, city) [Default City]:Xi`An
Organization Name (eg, company) [Default Company Ltd]:AAAA
Organizational Unit Name (eg, section) []:webserver
Common Name (eg, your name or your server's hostname) []:www.timinglee.org  
Email Address []:123@aaa.org 
[root@haproxy haproxy] ls /etc/haproxy/certs/
timinglee.org.crt  timinglee.org.key
[root@haproxy haproxy] cat /etc/haproxy/certs/timinglee.org.crt /etc/haproxy/certs/timinglee.org.key > /etc/haproxy/certs/timinglee.pem
[root@haproxy haproxy] ls /etc/haproxy/certs/ #将公钥和私钥全部导入pem中
timinglee.org.crt  timinglee.org.key  timinglee.pem
​

2.配置haproxy

listen web-https
    bind *:443 ssl crt /etc/haproxy/certs/timinglee.pem #注意一定要与生成从pem文件路径相同
    mode http
    balance roundrobin
    server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
    server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

全站加密

[root@haproxy haproxy]# vim /etc/haproxy/haproxy.cfg
frontend webcluster
    bind *:80
    mode http
    redirect scheme https if !{ ssl_fc } #进行全站加密
​

haproxy的配置文件还能写在子配置文件中

#将haproxy.cfg中的配置除了global和defaults其余全部注释,恢复最初未配置的环境
[root@haproxy haproxy] vim /lib/systemd/system/haproxy.service #打开haproxy的启动脚本
Environment="CONFIG=/etc/haproxy/haproxy.cfg" "PIDFILE=/run/haproxy.pid" "CFGDIR=/etc/haproxy/conf.d"
#Environment:环境,CONFIG=/etc/haproxy/haproxy.cfg:变量写在/etc/haproxy/haproxy.cfg,CONFIG=/etc/haproxy/haproxy.cfg :子配置文件的目录
[root@haproxy haproxy] cd /etc/haproxy/conf.d/
[root@haproxy conf.d] ll
total 0
[root@haproxy conf.d] vim webcluster.cfg #编写子配置文件
[root@haproxy conf.d]# cat webcluster.cfg 
listen stats
    mode http
    bind *:1234
    stats enable
    stats uri /status
    stats auth lee:lee
[root@haproxy conf.d]# systemctl restart haproxy.service 
Warning: The unit file, source configuration file or drop-ins of haproxy.service changed on disk. Run 'systemctl daemon-reload' to reload units.
#重启后会显示警告,只要打开过启动脚本的文件,都需要执行systemctl daemon-reload

  • 25
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值