1. HAProxy概述与环境规划
HAProxy是一款开源、高性能的负载均衡器和代理服务器,支持TCP和HTTP应用。它以稳定性、高性能和丰富的功能著称,广泛应用于大规模Web站点。更多学习教程www.fgedu.net.cn
1.1 HAProxy版本说明
HAProxy目前主要版本为2.8,本教程以HAProxy 2.8为例进行详细讲解。
$ haproxy -v
HAProxy 2.8.3-1.el8 2023/10/26 – https://haproxy.org/
Status: long-term supported branch – will stop receiving fixes around Q2 2028.
Known bugs: https://github.com/haproxy/haproxy/issues?q=is:issue+is:open
Running on: Linux 4.18.0-477.27.1.el8_8.x86_64 #1 SMP
# 查看编译选项
$ haproxy -vv
HAProxy 2.8.3-1.el8 2023/10/26
Build options :
TARGET = linux-glibc
CPU = generic
CC = gcc
CFLAGS = -O2 -g -pipe -Wall -Werror=format-security
OPTIONS = USE_PCRE2=1 USE_OPENSSL=1 USE_LUA=1 USE_SYSTEMD=1
1.2 环境规划
本次安装环境规划如下:
主机名:haproxy01.fgedu.net.cn
IP地址:192.168.1.51
VIP地址:192.168.1.100
HAProxy节点2:
主机名:haproxy02.fgedu.net.cn
IP地址:192.168.1.52
VIP地址:192.168.1.100
后端服务器节点1:
主机名:web01.fgedu.net.cn
IP地址:192.168.1.53
后端服务器节点2:
主机名:web02.fgedu.net.cn
IP地址:192.168.1.54
后端服务器节点3:
主机名:web03.fgedu.net.cn
IP地址:192.168.1.55
HAProxy版本:2.8.3
负载均衡算法:roundrobin
1.3 HAProxy核心特性
1. 高性能:单进程处理数万并发连接
2. 负载均衡:支持多种调度算法
3. 健康检查:支持TCP和HTTP健康检查
4. 会话保持:支持cookie和IP哈希
5. SSL终止:支持SSL/TLS卸载
6. ACL规则:灵活的访问控制
7. 监控页面:实时监控和统计
8. 连接限流:保护后端服务器
支持协议:
– TCP:纯TCP代理(数据库、邮件等)
– HTTP:HTTP/HTTPS代理和路由
– WebSocket:支持WebSocket代理
2. 硬件环境要求与检查
在安装HAProxy之前,需要对服务器硬件环境进行全面检查。学习交流加群风哥微信: itpux-com
2.1 最低硬件要求
CPU:1核心
内存:512MB
磁盘:1GB
推荐配置(生产环境):
CPU:2核心以上
内存:2GB以上
磁盘:10GB以上
高并发配置:
CPU:4核心以上
内存:4GB以上
网卡:10Gbps
2.2 系统环境检查
# cat /etc/redhat-release
Red Hat Enterprise Linux release 8.8 (Ootpa)
# 检查内核版本
# uname -r
4.18.0-477.27.1.el8_8.x86_64
# 检查内存信息
# free -h
total used free shared buff/cache available
Mem: 15Gi 1.0Gi 13Gi 256Mi 1.0Gi 14Gi
Swap: 7Gi 0B 7Gi
# 检查网络配置
# ip addr show eth0
2: eth0:
link/ether 00:50:56:a3:01:51 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.51/24 brd 192.168.1.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
2.3 依赖包安装
# yum install -y haproxy
# 输出示例:
Last metadata expiration check: 0:00:00 ago on Sat Apr 4 10:00:00 2026.
Dependencies resolved.
Installed:
haproxy-2.8.3-1.el8.x86_64
Complete!
# 安装Keepalived(高可用)
# yum install -y keepalived
# 验证安装
$ haproxy -v
HAProxy 2.8.3-1.el8 2023/10/26 – https://haproxy.org/
# 检查配置文件
$ ls -la /etc/haproxy/
total 8
drwxr-xr-x. 2 root root 24 Apr 4 10:00 .
drwxr-xr-x. 93 root root 8192 Apr 4 10:00 ..
-rw-r–r–. 1 root root 3142 Apr 4 10:00 haproxy.cfg
3. HAProxy安装步骤
本节详细介绍HAProxy的安装过程。学习交流加群风哥QQ113257174
3.1 创建目录结构
# mkdir -p /etc/haproxy/conf.d
# mkdir -p /var/lib/haproxy
# mkdir -p /var/log/haproxy
# 设置权限
# chown -R haproxy:haproxy /var/lib/haproxy
# chown -R haproxy:haproxy /var/log/haproxy
# 创建错误页面目录
# mkdir -p /etc/haproxy/errors
3.2 配置rsyslog
# vi /etc/rsyslog.d/haproxy.conf
$ModLoad imudp
$UDPServerRun 514
local0.* /var/log/haproxy/haproxy.log
local1.* /var/log/haproxy/haproxy_admin.log
# 重启rsyslog
# systemctl restart rsyslog
# 验证rsyslog状态
# systemctl status rsyslog
# 输出示例:
● rsyslog.service – System Logging Service
Loaded: loaded (/usr/lib/systemd/system/rsyslog.service; enabled; vendor preset: installed)
Active: active (running) since Sat 2026-04-04 10:00:00 CST; 1s ago
3.3 创建基础配置
# cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak
# 创建新配置
# vi /etc/haproxy/haproxy.cfg
global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
stats socket /var/lib/haproxy/stats mode 660 level admin
stats timeout 30s
user haproxy
group haproxy
daemon
maxconn 4000
pidfile /var/run/haproxy.pid
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5000
timeout client 50000
timeout server 50000
retries 3
option redispatch
maxconn 3000
# 验证配置
$ haproxy -c -f /etc/haproxy/haproxy.cfg
# 输出示例:
Configuration file is valid
3.4 启动HAProxy服务
# systemctl start haproxy
# 设置开机自启
# systemctl enable haproxy
# 检查状态
# systemctl status haproxy
# 输出示例:
● haproxy.service – HAProxy Load Balancer
Loaded: loaded (/usr/lib/systemd/system/haproxy.service; enabled; vendor preset: disabled)
Active: active (running) since Sat 2026-04-04 10:00:00 CST; 1s ago
Main PID: 12345 (haproxy)
Tasks: 2 (limit: 49134)
Memory: 5.5M
CGroup: /system.slice/haproxy.service
└─12345 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid
# 检查进程
# ps aux | grep haproxy
# 输出示例:
haproxy 12345 0.0 0.1 57896 2560 ? Ss 10:00 0:00 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid
haproxy 12346 0.0 0.2 89012 5120 ? S 10:00 0:00 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid
# 检查端口
# netstat -tlnp | grep haproxy
# 输出示例:
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 12346/haproxy
4. HAProxy参数配置
HAProxy参数配置是性能优化的关键步骤,直接影响系统性能。更多学习教程公众号风哥教程itpux_com
4.1 全局参数配置
# vi /etc/haproxy/haproxy.cfg
global
# 日志配置
log /dev/log local0
log /dev/log local1 notice
# 运行目录
chroot /var/lib/haproxy
# 统计socket
stats socket /var/lib/haproxy/stats mode 660 level admin
stats timeout 30s
# 运行用户
user haproxy
group haproxy
# 后台运行
daemon
# 最大连接数
maxconn 65535
# PID文件
pidfile /var/run/haproxy.pid
# 性能调优
nbproc 1
nbthread 4
cpu-map auto:1/1-4 0-3
# SSL配置
tune.ssl.default-dh-param 2048
ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
ssl-default-bind-options ssl-min-ver TLSv1.2
# 重载配置
# systemctl reload haproxy
4.2 默认参数配置
defaults
# 日志配置
log global
mode http
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
option redispatch
# 重试次数
retries 3
# 超时配置
timeout connect 10s
timeout client 300s
timeout server 300s
timeout http-keep-alive 10s
timeout http-request 10s
timeout queue 1m
timeout check 5s
# 最大连接数
maxconn 3000
# 错误页面
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
4.3 性能优化配置
# vi /etc/sysctl.d/99-haproxy.conf
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.ip_local_port_range = 1024 65535
fs.file-max = 2097152
# 使配置生效
# sysctl -p /etc/sysctl.d/99-haproxy.conf
# 用户限制
# vi /etc/security/limits.d/haproxy.conf
haproxy soft nofile 65535
haproxy hard nofile 65535
haproxy soft nproc 65535
haproxy hard nproc 65535
# 验证限制
$ ulimit -n
65535
5. 前端与后端配置
HAProxy的前端和后端配置是核心功能,本节介绍详细的配置方法。from:www.itpux.com
5.1 HTTP负载均衡配置
# vi /etc/haproxy/haproxy.cfg
frontend http_front
bind *:80
mode http
# 访问日志
log-format “%ci:%cp [%t] %ft %b/%s %Tq/%Tw/%Tc/%Tr/%Tt %ST %B %CC %CS %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq %hr %hs”
# ACL规则
acl is_static path_end .css .js .png .jpg .gif .ico
# 后端选择
use_backend static_servers if is_static
default_backend web_servers
backend web_servers
mode http
balance roundrobin
# 健康检查
option httpchk GET /health HTTP/1.1\r\nHost:\ localhost
# 会话保持
cookie SERVERID insert indirect nocache
# 后端服务器
server web01 192.168.1.53:80 check cookie s1 weight 3
server web02 192.168.1.54:80 check cookie s2 weight 2
server web03 192.168.1.55:80 check cookie s3 weight 1 backup
backend static_servers
mode http
balance roundrobin
# 后端服务器
server static01 192.168.1.53:80 check
server static02 192.168.1.54:80 check backup
# 验证配置
$ haproxy -c -f /etc/haproxy/haproxy.cfg
Configuration file is valid
# 重载配置
# systemctl reload haproxy
5.2 TCP负载均衡配置
# vi /etc/haproxy/haproxy.cfg
frontend mysql_front
bind *:3306
mode tcp
option tcplog
# 后端选择
default_backend mysql_servers
backend mysql_servers
mode tcp
balance roundrobin
# 健康检查
option mysql-check user haproxy_check
option tcp-check
tcp-check connect
tcp-check send PING\r\n
tcp-check expect string +PONG
# 后端服务器
server mysql01 192.168.1.53:3306 check weight 3
server mysql02 192.168.1.54:3306 check weight 2
server mysql03 192.168.1.55:3306 check weight 1 backup
# TCP负载均衡配置(Redis)
frontend redis_front
bind *:6379
mode tcp
option tcplog
default_backend redis_servers
backend redis_servers
mode tcp
balance roundrobin
# 健康检查
option tcp-check
tcp-check send PING\r\n
tcp-check expect string +PONG
# 后端服务器
server redis01 192.168.1.53:6379 check
server redis02 192.168.1.54:6379 check backup
# 重载配置
# systemctl reload haproxy
5.3 多端口配置
# vi /etc/haproxy/haproxy.cfg
frontend http_front
bind *:80
bind *:8080
mode http
# 根据端口选择后端
acl is_8080 dst_port 8080
use_backend api_servers if is_8080
default_backend web_servers
frontend https_front
bind *:443 ssl crt /etc/haproxy/ssl/fgedu.pem
mode http
# HTTP/2支持
option http-use-htx
http-request set-header X-Forwarded-Proto https
default_backend web_servers
backend web_servers
mode http
balance roundrobin
server web01 192.168.1.53:80 check
server web02 192.168.1.54:80 check
backend api_servers
mode http
balance roundrobin
server api01 192.168.1.53:8080 check
server api02 192.168.1.54:8080 check
# 重载配置
# systemctl reload haproxy
6. ACL规则配置
HAProxy的ACL规则功能强大,可以实现灵活的请求路由和访问控制。更多学习教程www.fgedu.net.cn
6.1 基于路径的ACL
# vi /etc/haproxy/haproxy.cfg
frontend http_front
bind *:80
mode http
# ACL规则
acl is_api path_beg /api
acl is_admin path_beg /admin
acl is_static path_end .css .js .png .jpg .gif .ico
# 后端选择
use_backend api_servers if is_api
use_backend admin_servers if is_admin
use_backend static_servers if is_static
default_backend web_servers
backend api_servers
mode http
balance roundrobin
server api01 192.168.1.53:8080 check
server api02 192.168.1.54:8080 check
backend admin_servers
mode http
balance roundrobin
server admin01 192.168.1.53:9090 check
server admin02 192.168.1.54:9090 check
backend static_servers
mode http
balance roundrobin
server static01 192.168.1.53:80 check
server static02 192.168.1.54:80 check
backend web_servers
mode http
balance roundrobin
server web01 192.168.1.53:80 check
server web02 192.168.1.54:80 check
# 重载配置
# systemctl reload haproxy
6.2 基于域名的ACL
# vi /etc/haproxy/haproxy.cfg
frontend http_front
bind *:80
mode http
# ACL规则
acl is_www hdr_beg(host) -i www.fgedu.net.cn
acl is_api hdr_beg(host) -i api.fgedu.net.cn
acl is_admin hdr_beg(host) -i admin.fgedu.net.cn
# 后端选择
use_backend api_servers if is_api
use_backend admin_servers if is_admin
default_backend web_servers
backend web_servers
mode http
balance roundrobin
server web01 192.168.1.53:80 check
server web02 192.168.1.54:80 check
backend api_servers
mode http
balance roundrobin
server api01 192.168.1.53:8080 check
server api02 192.168.1.54:8080 check
backend admin_servers
mode http
balance roundrobin
server admin01 192.168.1.53:9090 check
server admin02 192.168.1.54:9090 check
# 重载配置
# systemctl reload haproxy
6.3 基于IP的访问控制
# vi /etc/haproxy/haproxy.cfg
frontend http_front
bind *:80
mode http
# ACL规则
acl is_allowed src 192.168.1.0/24 10.0.0.0/8
acl is_admin path_beg /admin
# 访问控制
http-request deny if is_admin !is_allowed
# 后端选择
default_backend web_servers
backend web_servers
mode http
balance roundrobin
server web01 192.168.1.53:80 check
server web02 192.168.1.54:80 check
# 测试访问
$ curl -I http://192.168.1.51/admin/
# 输出示例(拒绝访问):
HTTP/1.0 403 Forbidden
Cache-Control: no-cache
Connection: close
Content-Type: text/html
# 重载配置
# systemctl reload haproxy
7. SSL/TLS配置
HAProxy支持SSL/TLS终止,可以卸载后端服务器的SSL计算压力。学习交流加群风哥微信: itpux-com
7.1 SSL证书配置
# mkdir -p /etc/haproxy/ssl
# 生成自签名证书(测试用)
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/haproxy/ssl/fgedu.key \
-out /etc/haproxy/ssl/fgedu.crt \
-subj “/C=CN/ST=BJ/L=BJ/O=FGedu/OU=IT/CN=*.fgedu.net.cn”
# 合并证书和密钥
# cat /etc/haproxy/ssl/fgedu.crt /etc/haproxy/ssl/fgedu.key > /etc/haproxy/ssl/fgedu.pem
# 设置权限
# chmod 600 /etc/haproxy/ssl/fgedu.pem
# chown haproxy:haproxy /etc/haproxy/ssl/fgedu.pem
# 验证证书
$ openssl x509 -in /etc/haproxy/ssl/fgedu.pem -text -noout
# 输出示例:
Certificate:
Data:
Version: 3 (0x2)
Serial Number:
12:34:56:78:90:ab:cd:ef
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=CN, ST=BJ, L=BJ, O=FGedu, OU=IT, CN=*.fgedu.net.cn
Validity
Not Before: Apr 4 10:00:00 2026 GMT
Not After : Apr 4 10:00:00 2027 GMT
Subject: C=CN, ST=BJ, L=BJ, O=FGedu, OU=IT, CN=*.fgedu.net.cn
7.2 HTTPS前端配置
# vi /etc/haproxy/haproxy.cfg
frontend https_front
bind *:443 ssl crt /etc/haproxy/ssl/fgedu.pem alpn h2,http/1.1
mode http
# HTTP/2支持
option http-use-htx
# 安全头部
http-response set-header Strict-Transport-Security “max-age=31536000; includeSubDomains”
http-response set-header X-Frame-Options “SAMEORIGIN”
http-response set-header X-XSS-Protection “1; mode=block”
http-response set-header X-Content-Type-Options “nosniff”
# 后端选择
default_backend web_servers
frontend http_front
bind *:80
mode http
# HTTP重定向到HTTPS
redirect scheme https code 301 if !{ ssl_fc }
backend web_servers
mode http
balance roundrobin
server web01 192.168.1.53:80 check
server web02 192.168.1.54:80 check
# 验证配置
$ haproxy -c -f /etc/haproxy/haproxy.cfg
Configuration file is valid
# 重载配置
# systemctl reload haproxy
# 测试HTTPS
$ curl -k https://192.168.1.51/
# 输出示例:
HTTP/2 200
server: nginx/1.24.0
strict-transport-security: max-age=31536000; includeSubDomains
x-frame-options: SAMEORIGIN
7.3 多证书配置
# vi /etc/haproxy/haproxy.cfg
frontend https_front
bind *:443 ssl crt /etc/haproxy/ssl/fgedu.pem crt /etc/haproxy/ssl/other.pem
mode http
# SNI支持
acl is_fgedu ssl_fc_sni_end fgedu.net.cn
acl is_other ssl_fc_sni_end other.com
# 后端选择
use_backend fgedu_servers if is_fgedu
use_backend other_servers if is_other
default_backend web_servers
backend fgedu_servers
mode http
balance roundrobin
server web01 192.168.1.53:80 check
server web02 192.168.1.54:80 check
backend other_servers
mode http
balance roundrobin
server web03 192.168.1.55:80 check
# 重载配置
# systemctl reload haproxy
8. 监控与运维
HAProxy提供了完善的监控和管理功能,本节介绍常用的运维方法。更多学习教程公众号风哥教程itpux_com
8.1 统计页面配置
# vi /etc/haproxy/haproxy.cfg
frontend stats
bind *:8404
mode http
stats enable
stats uri /haproxy-stats
stats refresh 10s
stats admin if LOCALHOST
stats auth admin:admin123
stats show-legends
stats show-node
# 验证配置
$ haproxy -c -f /etc/haproxy/haproxy.cfg
Configuration file is valid
# 重载配置
# systemctl reload haproxy
# 访问统计页面
$ curl -u admin:admin123 http://192.168.1.51:8404/haproxy-stats
# 输出示例:
# HAProxy Statistics Report
# pid: 12345
# uptime: 1d 2h 3m
# …
8.2 健康检查配置
backend web_servers
mode http
balance roundrobin
# HTTP健康检查
option httpchk GET /health HTTP/1.1\r\nHost:\ localhost
# 健康检查参数
server web01 192.168.1.53:80 check inter 5s fall 3 rise 2 weight 3
server web02 192.168.1.54:80 check inter 5s fall 3 rise 2 weight 2
server web03 192.168.1.55:80 check inter 5s fall 3 rise 2 weight 1
# TCP健康检查
backend mysql_servers
mode tcp
balance roundrobin
# TCP健康检查
option tcp-check
tcp-check connect
tcp-check send PING\r\n
tcp-check expect string +PONG
server mysql01 192.168.1.53:3306 check inter 5s fall 3 rise 2
server mysql02 192.168.1.54:3306 check inter 5s fall 3 rise 2
# MySQL健康检查
backend mysql_servers
mode tcp
balance roundrobin
# MySQL健康检查
option mysql-check user haproxy_check post-41
server mysql01 192.168.1.53:3306 check
server mysql02 192.168.1.54:3306 check
# 参数说明:
# inter:检查间隔时间
# fall:连续失败次数后标记为down
# rise:连续成功次数后标记为up
8.3 运维命令
# systemctl status haproxy
# 重载配置(平滑重启)
# systemctl reload haproxy
# 重启服务
# systemctl restart haproxy
# 查看连接统计
# echo “show stat” | socat stdio /var/lib/haproxy/stats
# 输出示例:
# pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,lbtot,tracked,type,rate,rate_lim,rate_max,check_status,check_code,check_duration,hrsp_1xx,hrsp_2xx,hrsp_3xx,hrsp_4xx,hrsp_5xx,hrsp_other,hanafail,req_rate,req_rate_max,req_tot,cli_abrt,srv_abrt,comp_in,comp_out,comp_byp,comp_rsp,lastsess,last_chk,last_agt,qtime,ctime,rtime,ttime,
http_front,FRONTEND,,,0,10,3000,100,50000,250000,0,0,0,,,,,OPEN,,,,,,,,,1,2,0,,,,0,5,0,10,,,,0,80,10,10,0,0,,,,0,,,,,,0,,,,,,,,
# 查看后端服务器状态
# echo “show servers state” | socat stdio /var/lib/haproxy/stats
# 输出示例:
1
# be_id be_name srv_id srv_name srv_addr srv_op_state srv_admin_state srv_uweight srv_iweight srv_time_since_last_change srv_check_status srv_check_result srv_check_health srv_check_state srv_agent_state bk_f_forced_id srv_f_forced_id srv_f_qtime
2 web_servers 1 web01 192.168.1.53 2 0 3 3 3600 6 3 7 6 0 0 0 0
2 web_servers 2 web02 192.168.1.54 2 0 2 2 3600 6 3 7 6 0 0 0 0
# 禁用后端服务器
# echo “disable server web_servers/web01” | socat stdio /var/lib/haproxy/stats
# 启用后端服务器
# echo “enable server web_servers/web01” | socat stdio /var/lib/haproxy/stats
# 设置服务器权重
# echo “set weight web_servers/web01 5” | socat stdio /var/lib/haproxy/stats
9. 升级与迁移
HAProxy升级和迁移是运维工作中的重要环节,需要仔细规划和执行。from:www.itpux.com
9.1 版本升级
$ haproxy -v
HAProxy 2.6.12
# 备份配置
# cp /etc/haproxy/haproxy.cfg /backup/haproxy_$(date +%Y%m%d).cfg
# 升级HAProxy
# yum update haproxy
# 输出示例:
Upgraded:
haproxy-2.8.3-1.el8.x86_64
Complete!
# 验证版本
$ haproxy -v
HAProxy 2.8.3-1.el8 2023/10/26
# 验证配置
$ haproxy -c -f /etc/haproxy/haproxy.cfg
Configuration file is valid
# 重启服务
# systemctl restart haproxy
9.2 配置迁移
# tar -czf haproxy_backup_$(date +%Y%m%d).tar.gz \
/etc/haproxy \
/var/lib/haproxy
# 迁移到新服务器
# scp haproxy_backup_*.tar.gz root@newserver:/backup/
# 在新服务器解压
# tar -xzf haproxy_backup_*.tar.gz -C /
# 验证配置
$ haproxy -c -f /etc/haproxy/haproxy.cfg
Configuration file is valid
# 启动服务
# systemctl start haproxy
10. 生产环境实战案例
本节提供一个完整的生产环境配置案例,帮助读者更好地理解HAProxy的实际应用。更多学习教程www.fgedu.net.cn
10.1 生产环境完整配置
# vi /etc/haproxy/haproxy.cfg
global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
stats socket /var/lib/haproxy/stats mode 660 level admin
stats timeout 30s
user haproxy
group haproxy
daemon
maxconn 65535
pidfile /var/run/haproxy.pid
nbproc 1
nbthread 4
cpu-map auto:1/1-4 0-3
tune.ssl.default-dh-param 2048
ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
ssl-default-bind-options ssl-min-ver TLSv1.2
defaults
log global
mode http
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
option redispatch
retries 3
timeout connect 10s
timeout client 300s
timeout server 300s
timeout http-keep-alive 10s
timeout http-request 10s
timeout queue 1m
timeout check 5s
maxconn 3000
frontend http_front
bind *:80
mode http
# HTTP重定向到HTTPS
redirect scheme https code 301 if !{ ssl_fc }
# ACL规则
acl is_api path_beg /api
acl is_admin path_beg /admin
# 后端选择
use_backend api_servers if is_api
use_backend admin_servers if is_admin
frontend https_front
bind *:443 ssl crt /etc/haproxy/ssl/fgedu.pem alpn h2,http/1.1
mode http
option http-use-htx
# 安全头部
http-response set-header Strict-Transport-Security “max-age=31536000; includeSubDomains”
http-response set-header X-Frame-Options “SAMEORIGIN”
http-response set-header X-XSS-Protection “1; mode=block”
http-response set-header X-Content-Type-Options “nosniff”
# ACL规则
acl is_api path_beg /api
acl is_admin path_beg /admin
acl is_allowed src 192.168.1.0/24 10.0.0.0/8
# 访问控制
http-request deny if is_admin !is_allowed
# 后端选择
use_backend api_servers if is_api
use_backend admin_servers if is_admin
default_backend web_servers
backend web_servers
mode http
balance roundrobin
option httpchk GET /health HTTP/1.1\r\nHost:\ localhost
cookie SERVERID insert indirect nocache
server web01 192.168.1.53:80 check cookie s1 weight 3
server web02 192.168.1.54:80 check cookie s2 weight 2
server web03 192.168.1.55:80 check cookie s3 weight 1 backup
backend api_servers
mode http
balance roundrobin
option httpchk GET /api/health HTTP/1.1\r\nHost:\ localhost
server api01 192.168.1.53:8080 check weight 3
server api02 192.168.1.54:8080 check weight 2
backend admin_servers
mode http
balance roundrobin
option httpchk GET /admin/health HTTP/1.1\r\nHost:\ localhost
server admin01 192.168.1.53:9090 check
server admin02 192.168.1.54:9090 check backup
frontend stats
bind *:8404
mode http
stats enable
stats uri /haproxy-stats
stats refresh 10s
stats admin if LOCALHOST
stats auth admin:admin123
stats show-legends
stats show-node
10.2 高可用配置
# vi /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id HAPROXY_MASTER
}
vrrp_script check_haproxy {
script “killall -0 haproxy”
interval 2
weight -20
fall 3
rise 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass fgedu2026
}
virtual_ipaddress {
192.168.1.100/24 dev eth0 label eth0:0
}
track_script {
check_haproxy
}
}
# Keepalived配置(Backup节点)
# vi /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id HAPROXY_BACKUP
}
vrrp_script check_haproxy {
script “killall -0 haproxy”
interval 2
weight -20
fall 3
rise 2
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass fgedu2026
}
virtual_ipaddress {
192.168.1.100/24 dev eth0 label eth0:0
}
track_script {
check_haproxy
}
}
# 启动Keepalived
# systemctl start keepalived
# systemctl enable keepalived
10.3 性能调优实战
$ ab -n 100000 -c 1000 http://192.168.1.100/
# 输出示例:
Server Software: nginx/1.24.0
Server Hostname: 192.168.1.100
Server Port: 80
Concurrency Level: 1000
Time taken for tests: 10.000 seconds
Complete requests: 100000
Failed requests: 0
Requests per second: 10000.00 [#/sec] (mean)
Time per request: 100.000 [ms] (mean)
# 查看HAProxy统计
$ curl -u admin:admin123 http://192.168.1.51:8404/haproxy-stats
# 输出示例:
# HAProxy Statistics Report
# pid: 12345
# uptime: 1d 2h 3m
# Total sessions: 100000
# Total bytes in: 5000000
# Total bytes out: 25000000
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
