banner
约 600 字
2 分钟

HAproxy 四层转发

摘要

本文介绍了在 Ubuntu 服务器上安装、配置及调优 HAProxy 的完整流程。安装环节包含更新源、部署软件及设置开机自启。配置部分重点设置 TCP 转发,涵盖全局参数、统计页面及前后端定义。调优阶段通过调整内核参数和增加文件句柄限制来优化性能。最后演示了配置检查、重载及状态查看的操作。

这里的演示是使用的 ubuntu 服务器,其他的发行版同理

安装配置

安装

纯文本
apt update
apt install haproxy -y

查看版本:

纯文本
haproxy -v

设置开机启动:

纯文本
systemctl enable haproxy

TCP 转发配置

配置文件:

纯文本
vim /etc/haproxy/haproxy.cfg
纯文本
global
​        # 增加下面这2句nbthread推荐设置为 cpu 核数
        maxconn 200000
        nbthread 8
listen stats
        bind *:8405
        mode http
        stats enable
        stats uri /stats
        stats refresh 5s
        stats auth admin:密码123
        stats hide-version
        stats show-node
​
        timeout connect 5s
        timeout client 30s
        timeout server 30s
​
defaults
        log     global
        mode    tcp
        option  tcplog
        option  dontlognull
        timeout connect 5000
        timeout client 2h
        timeout server 2h
        timeout tunnel 2h
​
frontend <名称>
        bind *:15556<监听端口>
        default_backend backend_test<后端>
​
backend backend_test<后端>
        balance leastconn
        server node1 5.2.0.47:15556 check
        server node1 5.2.0.48:15556 check

调优

纯文本
cat > /etc/sysctl.d/99-haproxy.conf <<'EOF'
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 250000
​
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_syncookies = 1
​
net.ipv4.ip_local_port_range = 10000 65000
​
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15
​
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 5
​
net.core.rmem_max = 134217728
net.core.wmem_max = 134217728
net.ipv4.tcp_rmem = 4096 87380 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728
​
net.ipv4.tcp_slow_start_after_idle = 0
net.ipv4.tcp_mtu_probing = 1
EOF
​
sysctl --system

然后继续处理文件句柄:

纯文本
mkdir -p /etc/systemd/system/haproxy.service.d
​
cat > /etc/systemd/system/haproxy.service.d/override.conf <<'EOF'
[Service]
LimitNOFILE=1048576
EOF
​
systemctl daemon-reload
systemctl restart haproxy

检查 HAProxy 文件句柄:

纯文本
cat /proc/$(pidof haproxy | awk '{print $1}')/limits | grep "Max open files"

看到接近这个就对了:

纯文本
Max open files            1048576

重载进程

修改好配置文件

纯文本
vi /etc/haproxy/haproxy.cfg

检查配置文件是否通过语法校验

纯文本
haproxy -c -f /etc/haproxy/haproxy.cfg && echo "配置检查通过"

重载

纯文本
systemctl reload haproxy

查看状态

纯文本
systemctl status haproxy --no-pager

END