Linux HAProxy 详解与实战教程

HAProxy 简介

HAProxy 是一款开源软件,由法国开发者 Willy Tarreau 在2000年使用C语言开发,它是一款具备高并发、高性能的TCP和HTTP负载均衡器。HAProxy 支持基于cookie的持久性、自动故障切换,以及正则表达式和web状态统计。
在这里插入图片描述

HAProxy 实战环境部署

前提条件

确保所有主机的防火墙均为关闭状态。

环境搭建

克隆三台虚拟机 RHEL9.4,分别为 haproxy、webserver1、webserver2 三台主机。

  • haproxy:网卡 eth0、IP 为 172.25.254.100、主机名为 haproxy.example.com
  • webserver1:网卡 eth0、IP 为 172.25.254.10、主机名为 webserver1.example.com
  • webserver2:网卡 eth0、IP 为 172.25.254.20、主机名为 webserver2.example.com

在两台 webserver 上安装 nginx:

dnf install nginx -y
echo "webserver1:172.25.254.10" > /usr/share/nginx/html/index.html
systemctl enable --now nginx.service

同样步骤对 webserver2 进行操作,只是将内容改为 webserver2:172.25.254.20

HAProxy 基本配置

HAProxy 的配置文件 haproxy.cfg 由两大部分组成:global(全局配置段)和 proxies(代理配置段)。

Global 配置
  • 进程及安全配置相关的参数
  • 性能调整相关参数
  • Debug 参数
Proxies 配置
  • defaults:为 frontend, backend, listen 提供默认配置
  • frontend:前端,相当于 nginx 中的 server {}
  • backend:后端,相当于 nginx 中的 upstream {}
  • listen:同时拥有前端和后端配置,配置简单,生产推荐使用

配置示例

frontend webcluster
bind *:80
mode http
use_backend webcluster-host

backend webcluster-host
balance roundrobin
server web1 172.25.254.10:80
server web2 172.25.254.20:80

重启 HAProxy 服务:

systemctl restart haproxy.service
systemctl enable haproxy.service

测试访问

使用 curl 命令测试 HAProxy 负载均衡效果:

curl 172.25.254.100

HAProxy 详解

负载均衡算法

HAProxy 支持多种负载均衡算法,包括静态和动态算法:

  • 静态算法:static-rr(基于权重的轮询调度)、first(很少用)
  • 动态算法:roundrobin(使用最多)、leastconn、random
  • 其他算法:source、map-base 取模法、一致性hash、uri、url_param、hdr

高级功能及配置

  • HAProxy 的状态页面监控
  • 基于 cookie 的会话保持
  • IP 透传:七层 IP 透传和四层透传
  • ACL 访问控制列表:利用 ACL 做动静分离访问控制

基于后缀名实现动静分离

可以通过配置 ACL 规则来实现基于后缀名的动静分离:

acl static_file urlpfx /static/ /images/ /javascript/ /css/
use_backend static_server if static_file

基于访问路径实现动静分离

acl dynamic_path urlp /api/ /user/
use_backend dynamic_server if dynamic_path

基于 HTTP 重定向错误页面

errorfile 403 /etc/haproxy/errorfiles/403.http
errorfile 500 /etc/haproxy/errorfiles/500.http

通过这些配置,HAProxy 可以更加灵活地处理不同的业务需求,实现高效的负载均衡和流量管理。

猜你喜欢

转载自blog.csdn.net/qq_40797754/article/details/143354804