赞
踩
HAProxy是法国开发者威利塔罗(Willy Tarreau) 在2000年使用C语言开发的一个开源软件,是一款具备高并发(一万以上)、高性能的TCP和HTTP负载均衡器,支持基于cookie的持久性,自动故障切换,支持正则表达式及web状态统计,目前最新TLS版本为2.8。
HAProxy 是一款免费、快速、可靠的反向代理服务器,可为基于 TCP 和 HTTP 的应用程序提供高可用性、负载平衡和代理服务。它特别适用于流量非常大的网站,并为世界上访问量最大的网站中的很大一部分提供支持。多年来,它已成为事实上的标准开源负载平衡器,现在随大多数主流 Linux 发行版一起提供,并通常默认部署在云平台中。
从2013年HAProxy 分为社区版和企业版,企业版将提供更多的特性和功能以及全天24小时的技术支持等服务。
图1-1 Haproxy企业版图标
企业版网站:https://www.haproxy.com/
图1-2 Haproxy企业版网站
图1-3 Haproxy社区版图标
社区版网站:http://www.haproxy.org/
github:https://github.com/haproxy
图1-4 Haproxy社区版网站
功能 | 社区版 | 企业版 |
---|---|---|
高级HTTP / TCP负载平衡和持久性 | 支持 | 支持 |
高级健康检查 | 支持 | 支持 |
应用程序加速 | 支持 | 支持 |
高级安全特性 | 支持 | 支持 |
高级管理 | 支持 | 支持 |
HAProxy Dev Branch新功能 | 支持 | |
24*7 支持服务 | 支持 | |
实时仪表盘 | 支持 | |
VRRP和Route Health Injection HA工具 | 支持 | |
ACL,映射和TLS票证密钥同步 | 支持 | |
基于应用程序的高级DDoS和Bot保护(自动保护) | 支持 | |
Bot(机器人)监测 | 支持 | |
Web应用防火墙 | 支持 | |
HTTP协议验证 | 支持 | |
实时集群追踪 | 支持 |
HAProxy具有以下主要功能:
总的来说,HAProxy是一个功能强大、可靠和高性能的负载均衡软件,它提供了多种功能和配置选项,可以满足不同应用场景下的负载均衡需求。
图1-5 Haproxy架构图
支持功能:
图1-6 Haproxy支持的功能
不具备的功能:
Rocky 9和CentOS Stream 9:
# Rocky 9和CentOS Stream 9默认支持修改网卡名。
[root@rocky9 ~]# grep 'plugins' /etc/NetworkManager/NetworkManager.conf
#plugins=keyfile,ifcfg-rh
# 因为网卡命名方式默认是keyfile,默认不支持修改网卡名,既然官方已经默认是keyfile那这里就不去更改网卡名了。
[root@rocky9 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`
[root@rocky9 ~]# nmcli con delete ${ETHNAME} && nmcli connection add type ethernet con-name ${ETHNAME} ifname ${ETHNAME} ipv4.method manual ipv4.address "172.31.0.9/21" ipv4.gateway "172.31.0.2" ipv4.dns "223.5.5.5,180.76.76.76" autoconnect yes && nmcli con reload && nmcli con up ${ETHNAME}
# 172.31.0.9/21中172.31.0.9是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。
[root@rocky9 ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:0c:29:37:62:95 brd ff:ff:ff:ff:ff:ff
altname enp3s0
inet 172.31.0.9/21 brd 172.31.7.255 scope global noprefixroute ens160
valid_lft forever preferred_lft forever
inet6 fe80::51ca:fd5d:3552:677d/64 scope link noprefixroute
valid_lft forever preferred_lft forever
# 可以看到ip地址已修改。
Rocky 8、CentOS Stream 8和CentOS 7:
# Rocky 8、CentOS Stream 8和CentOS 7支持修改网卡名。
[root@rocky8 ~]# grep 'plugins' /etc/NetworkManager/NetworkManager.conf
#plugins=ifcfg-rh
# 因为网卡命名方式默认是ifcfg-rh,支持修改网卡名。
# 修改网卡名称配置文件
[root@rocky8 ~]# sed -ri.bak '/^GRUB_CMDLINE_LINUX=/s@"$@ net.ifnames=0 biosdevname=0"@' /etc/default/grub
[root@rocky8 ~]# grub2-mkconfig -o /boot/grub2/grub.cfg
Generating grub configuration file ...
done
# 修改网卡文件名
[root@rocky8 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`
[root@rocky8 ~]# mv /etc/sysconfig/network-scripts/ifcfg-${ETHNAME} /etc/sysconfig/network-scripts/ifcfg-eth0
[root@rocky8 ~]# shutdown -r now
[root@rocky8 ~]# nmcli dev
DEVICE TYPE STATE CONNECTION
eth0 ethernet connected Wired connection 1
lo loopback unmanaged --
# 可以看到CONNECTION的名字是Wired connection 1,要改名才可以下面设置。
[root@rocky8 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`
[root@rocky8 ~]# nmcli connection modify "Wired connection 1" con-name ${ETHNAME}
[root@rocky8 ~]# nmcli dev
DEVICE TYPE STATE CONNECTION
eth0 ethernet connected eth0
lo loopback unmanaged --
# 修改ip地址
[root@rocky8 ~]# nmcli con delete ${ETHNAME} && nmcli connection add type ethernet con-name ${ETHNAME} ifname ${ETHNAME} ipv4.method manual ipv4.address "172.31.0.8/21" ipv4.gateway "172.31.0.2" ipv4.dns "223.5.5.5,180.76.76.76" autoconnect yes && nmcli con reload && nmcli dev up eth0
# 172.31.0.8/21中172.31.0.8是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。
[root@rocky8 ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:0c:29:6f:65:d3 brd ff:ff:ff:ff:ff:ff
altname enp3s0
altname ens160
inet 172.31.0.8/21 brd 172.31.7.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::e9c9:aa93:4a58:2cc2/64 scope link noprefixroute
valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。
Ubuntu:
# Ubuntu先启用root用户,并设置密码
raymond@ubuntu2204:~$ cat set_root_login.sh
#!/bin/bash
read -p "请输入密码: " PASSWORD
echo ${PASSWORD} |sudo -S sed -ri 's@#(PermitRootLogin )prohibit-password@\1yes@' /etc/ssh/sshd_config
sudo systemctl restart sshd
sudo -S passwd root <<-EOF
${PASSWORD}
${PASSWORD}
EOF
raymond@ubuntu2204:~$ bash set_root_login.sh
请输入密码: 123456
[sudo] password for raymond: New password: Retype new password: passwd: password updated successfully
raymond@ubuntu2204:~$ rm -rf set_root_login.sh
# 使用root登陆,修改网卡名
root@ubuntu2204:~# sed -ri.bak '/^GRUB_CMDLINE_LINUX=/s@"$@net.ifnames=0 biosdevname=0"@' /etc/default/grub
root@ubuntu2204:~# grub-mkconfig -o /boot/grub/grub.cfg
Sourcing file `/etc/default/grub'
Sourcing file `/etc/default/grub.d/init-select.cfg'
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-5.15.0-88-generic
Found initrd image: /boot/initrd.img-5.15.0-88-generic
Warning: os-prober will not be executed to detect other bootable partitions.
Systems on them will not be added to the GRUB boot configuration.
Check GRUB_DISABLE_OS_PROBER documentation entry.
done
# Ubuntu 20.04设置ip地址
root@ubuntu2004:~# cat > /etc/netplan/00-installer-config.yaml <<-EOF
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: no
dhcp6: no
addresses: [172.31.0.20/21]
gateway4: 172.31.0.2
nameservers:
addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu20.04网卡配置文件是00-installer-config.yaml;172.31.0.20/21中172.31.0.20是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。
# Ubuntu 18.04设置ip地址
root@ubuntu1804:~# cat > /etc/netplan/01-netcfg.yaml <<-EOF
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: no
dhcp6: no
addresses: [172.31.0.18/21]
gateway4: 172.31.0.2
nameservers:
addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu18.04网卡配置文件是01-netcfg.yaml;172.31.0.18/21中172.31.0.18是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。
root@ubuntu2004:~# shutdown -r now
root@ubuntu2004:~# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:0c:29:e5:98:6f brd ff:ff:ff:ff:ff:ff
inet 172.31.0.20/21 brd 172.31.7.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fee5:986f/64 scope link
valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。
# Ubuntu 22.04设置ip地址
root@ubuntu2204:~# cat > /etc/netplan/00-installer-config.yaml <<-EOF
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: no
dhcp6: no
addresses: [172.31.0.22/21]
routes:
- to: default
via: 172.31.0.2
nameservers:
addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu 22.04网卡配置文件是00-installer-config.yaml;172.31.0.22/21中172.31.0.22是ip地址,21是子网位数;172.31.0.2是网关地址,Ubuntu 22.04设置网关地址的方法发生了改变,参考上面的方法;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。
root@ubuntu2204:~# shutdown -r now
# 重启后使用新设置的ip登陆
root@ubuntu2204:~# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:0c:29:a7:be:f2 brd ff:ff:ff:ff:ff:ff
altname enp2s1
altname ens33
inet 172.31.0.22/21 brd 172.31.7.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fea7:bef2/64 scope link
valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。
Rocky 8和9:
MIRROR=mirrors.sjtug.sjtu.edu.cn
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://dl.rockylinux.org/$contentdir|baseurl=https://'${MIRROR}'/rocky|g' /etc/yum.repos.d/[Rr]ocky*.repo
dnf clean all && dnf makecache
CentOS Stream 9:
cat update_mirror.pl
#!/usr/bin/perl
use strict;
use warnings;
use autodie;
# 要修改镜像源,请去修改url变量!
my $url = 'mirrors.aliyun.com';
my $mirrors = "https://$url/centos-stream";
if (@ARGV < 1) {
die "Usage: $0 <filename1> <filename2> ...\n";
}
while (my $filename = shift @ARGV) {
my $backup_filename = $filename . '.bak';
rename $filename, $backup_filename;
open my $input, "<", $backup_filename;
open my $output, ">", $filename;
while (<$input>) {
s/^metalink/# metalink/;
if (m/^name/) {
my (undef, $repo, $arch) = split /-/;
$repo =~ s/^\s+|\s+$//g;
($arch = defined $arch ? lc($arch) : '') =~ s/^\s+|\s+$//g;
if ($repo =~ /^Extras/) {
$_ .= "baseurl=${mirrors}/SIGs/\$releasever-stream/extras" . ($arch eq 'source' ? "/${arch}/" : "/\$basearch/") . "extras-common\n";
} else {
$_ .= "baseurl=${mirrors}/\$releasever-stream/$repo" . ($arch eq 'source' ? "/" : "/\$basearch/") . ($arch ne '' ? "${arch}/tree/" : "os") . "\n";
}
}
print $output $_;
}
}
rpm -q perl &> /dev/null || { echo -e "\\033[01;31m "安装perl工具,请稍等..."\033[0m";yum -y install perl ; }
perl ./update_mirror.pl /etc/yum.repos.d/centos*.repo
dnf clean all && dnf makecache
CentOS Stream 8:
MIRROR=mirrors.aliyun.com
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://mirror.centos.org/$contentdir|baseurl=https://'${MIRROR}'/centos|g' /etc/yum.repos.d/CentOS-*.repo
dnf clean all && dnf makecache
CentOS 7:
MIRROR=mirrors.aliyun.com
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://mirror.centos.org|baseurl=https://'${MIRROR}'|g' /etc/yum.repos.d/CentOS-*.repo
yum clean all && yum makecache
Ubuntu 22.04和20.04:
MIRROR=mirrors.aliyun.com
OLD_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu/? $(lsb_release -cs) main.*@\2@p" /etc/apt/sources.list`
sed -i.bak 's/'${OLD_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list
apt update
Ubuntu 18.04:
MIRROR=mirrors.aliyun.com
OLD_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu/? $(lsb_release -cs) main.*@\2@p" /etc/apt/sources.list`
sed -i.bak 's/'${OLD_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list
SECURITY_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu $(lsb_release -cs)-security main.*@\2@p" /etc/apt/sources.list`
sed -i.bak 's/'${SECURITY_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list
apt update
# Rocky和CentOS
systemctl disable --now firewalld
# CentOS 7
systemctl disable --now NetworkManager
# Ubuntu
systemctl disable --now ufw
#CentOS
setenforce 0
sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config
#Ubuntu
Ubuntu没有安装SELinux,不用设置
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
echo 'Asia/Shanghai' >/etc/timezone
#Ubuntu还要设置下面内容
cat >> /etc/default/locale <<-EOF
LC_TIME=en_DK.UTF-8
EOF
打开链接:https://haproxy.debian.net/,,选择合适的版本,会自动出现安装提示。
root@ubuntu2204:~# apt -y install --no-install-recommends software-properties-common
root@ubuntu2204:~# add-apt-repository -y ppa:vbernat/haproxy-2.8
root@ubuntu2204:~# apt update
root@ubuntu2204:~# apt-cache madison haproxy
haproxy | 2.8.5-1ppa1~jammy | https://ppa.launchpadcontent.net/vbernat/haproxy-2.8/ubuntu jammy/main amd64 Packages
haproxy | 2.4.24-0ubuntu0.22.04.1 | https://mirrors.aliyun.com/ubuntu jammy-updates/main amd64 Packages
haproxy | 2.4.22-0ubuntu0.22.04.3 | https://mirrors.aliyun.com/ubuntu jammy-security/main amd64 Packages
haproxy | 2.4.14-1ubuntu1 | https://mirrors.aliyun.com/ubuntu jammy/main amd64 Packages
# 安装指定版本
root@ubuntu2204:~# apt -y install haproxy=2.8.5-1ppa1~jammy
# 或安装最新版
apt install -y haproxy=2.8.\*
# 验证haproxy版本
root@ubuntu2204:~# haproxy -v
HAProxy version 2.8.5-1ppa1~jammy 2023/12/09 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2028.
Known bugs: http://www.haproxy.org/bugs/bugs-2.8.5.html
Running on: Linux 5.15.0-88-generic #98-Ubuntu SMP Mon Oct 2 15:18:56 UTC 2023 x86_64
[root@rocky9 ~]# yum list haproxy --showduplicates
Last metadata expiration check: 0:12:30 ago on Sat 27 Jan 2024 07:06:37 PM CST.
Available Packages
haproxy.x86_64 2.4.22-1.el9 appstrea
[root@rocky9 ~]# yum -y install haproxy
[root@rocky9 ~]# haproxy -v
HAProxy version 2.4.22-f8e3218 2023/02/14 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2026.
Known bugs: http://www.haproxy.org/bugs/bugs-2.4.22.html
Running on: Linux 5.14.0-362.8.1.el9_3.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Nov 8 17:36:32 UTC 2023 x86_64
编译安装HAProxy 2.8 LTS版本,更多源码包下载地址:http://www.haproxy.org/download/
HAProxy 支持基于lua实现功能扩展,lua是一种小巧的脚本语言,于1993年由巴西里约热内卢天主教大学(Pontifical Catholic University of Rio de Janeiro)里的一个研究小组开发,其设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制能。
Lua 官网:www.lua.org
Lua 应用场景
参考链接:https://www.lua.org/download.html
# 安装基础命令及编译依赖环境
# Rocky和CentOS
yum -y install gcc make readline-devel
# Ubuntu
apt update
apt -y install gcc make libreadline-dev
[root@rocky9-2 ~]# cd /usr/local/src/
[root@rocky9-2 src]# wget https://www.lua.org/ftp/lua-5.4.6.tar.gz
-bash: wget: command not found
[root@rocky9-2 src]# dnf -y install wget
[root@rocky9-2 src]# wget https://www.lua.org/ftp/lua-5.4.6.tar.gz
[root@rocky9-2 src]# tar xf lua-5.4.6.tar.gz
[root@rocky9-2 src]# cd lua-5.4.6
[root@rocky9-2 lua-5.4.6]# make linux test
# 查看编译安装的版本
[root@rocky9-2 lua-5.4.6]# src/lua -v
Lua 5.4.6 Copyright (C) 1994-2023 Lua.org, PUC-Rio
# HAProxy 1.8及1.9版本编译参数:
make ARCH=x86_64 TARGET=linux2628 USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_CPU_AFFINITY=1 PREFIX=/usr/local/haproxy
# HAProxy 2.0以上版本编译参数:
[root@rocky9-2 lua-5.4.6]# cd ..
# Rocky和CentOS
yum -y install openssl-devel pcre-devel systemd-devel zlib-devel
# Ubuntu
apt -y install openssl libssl-dev libpcre3 libpcre3-dev zlib1g-dev libsystemd-dev
[root@rocky9-2 src]# wget https://www.haproxy.org/download/2.8/src/haproxy-2.8.5.tar.gz
[root@rocky9-2 src]# tar xf haproxy-2.8.5.tar.gz
[root@rocky9-2 src]# cd haproxy-2.8.5
# 查看安装方法
[root@rocky9-2 haproxy-2.8.5]# cat README
[root@rocky9-2 haproxy-2.8.5]# cat INSTALL
# 参考INSTALL文件进行编译安装
[root@rocky9 haproxy-2.8.5]# make -j 2 ARCH=x86_64 TARGET=linux-glibc USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_CPU_AFFINITY=1 USE_LUA=1 LUA_INC=/usr/local/src/lua-5.4.6/src/ LUA_LIB=/usr/local/src/lua-5.4.6/src/
[root@rocky9 haproxy-2.8.5]# make install PREFIX=/apps/haproxy
[root@rocky9 haproxy-2.8.5]# tree /apps/haproxy/
-bash: tree: command not found
[root@rocky9 haproxy-2.8.5]# dnf -y install tree
# 查看生成的文件
[root@rocky9-2 haproxy-2.8.5]# tree /apps/haproxy/
/apps/haproxy/
├── doc
│ └── haproxy
│ ├── 51Degrees-device-detection.txt
│ ├── architecture.txt
│ ├── configuration.txt
│ ├── cookie-options.txt
│ ├── DeviceAtlas-device-detection.txt
│ ├── intro.txt
│ ├── linux-syn-cookies.txt
│ ├── lua.txt
│ ├── management.txt
│ ├── netscaler-client-ip-insertion-protocol.txt
│ ├── network-namespaces.txt
│ ├── peers.txt
│ ├── peers-v2.0.txt
│ ├── proxy-protocol.txt
│ ├── regression-testing.txt
│ ├── seamless_reload.txt
│ ├── SOCKS4.protocol.txt
│ ├── SPOE.txt
│ └── WURFL-device-detection.txt
├── sbin
│ └── haproxy
└── share
└── man
└── man1
└── haproxy.1
6 directories, 21 files
[root@rocky9-2 haproxy-2.8.5]# cd
[root@rocky9-2 ~]# ln -s /apps/haproxy/sbin/haproxy /usr/sbin/
[root@rocky9-2 ~]# which haproxy
/usr/sbin/haproxy
[root@rocky9-2 ~]# haproxy -v
HAProxy version 2.8.5-aaba8d0 2023/12/07 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2028.
Known bugs: http://www.haproxy.org/bugs/bugs-2.8.5.html
Running on: Linux 5.14.0-362.8.1.el9_3.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Nov 8 17:36:32 UTC 2023 x86_64
# 大写-V选项显示版本和帮助用法
[root@rocky9-2 ~]# haproxy -V
HAProxy version 2.8.5-aaba8d0 2023/12/07 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2028.
Known bugs: http://www.haproxy.org/bugs/bugs-2.8.5.html
Running on: Linux 5.14.0-362.8.1.el9_3.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Nov 8 17:36:32 UTC 2023 x86_64
Usage : haproxy [-f <cfgfile|cfgdir>]* [ -vdVD ] [ -n <maxconn> ] [ -N <maxpconn> ]
[ -p <pidfile> ] [ -m <max megs> ] [ -C <dir> ] [-- <cfgfile>*]
-v displays version ; -vv shows known build options.
-d enters debug mode ; -db only disables background mode.
-dM[<byte>,help,...] debug memory (default: poison with <byte>/0x50)
-V enters verbose mode (disables quiet mode)
-D goes daemon ; -C changes to <dir> before loading files.
-W master-worker mode.
-Ws master-worker mode with systemd notify support.
-q quiet mode : don't display messages
-c check mode : only check config files and exit
-cc check condition : evaluate a condition and exit
-n sets the maximum total # of connections (uses ulimit -n)
-m limits the usable amount of memory (in MB)
-N sets the default, per-proxy maximum # of connections (0)
-L set local peer name (default to hostname)
-p writes pids of all children to this file
-dC[[key],line] display the configuration file, if there is a key, the file will be anonymised
-de disables epoll() usage even when available
-dp disables poll() usage even when available
-dS disables splice usage (broken on old kernels)
-dG disables getaddrinfo() usage
-dR disables SO_REUSEPORT usage
-dL dumps loaded object files after config checks
-dK{class[,...]} dump registered keywords (use 'help' for list)
-dr ignores server address resolution failures
-dV disables SSL verify on servers side
-dW fails if any warning is emitted
-dD diagnostic mode : warn about suspicious configuration statements
-dF disable fast-forward
-sf/-st [pid ]* finishes/terminates old pids.
-x <unix_socket> get listening sockets from a unix socket
-S <bind>[,<bind options>...] new master CLI
[root@rocky9-2 ~]# haproxy -vv
HAProxy version 2.8.5-aaba8d0 2023/12/07 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2028.
Known bugs: http://www.haproxy.org/bugs/bugs-2.8.5.html
Running on: Linux 5.14.0-362.8.1.el9_3.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Nov 8 17:36:32 UTC 2023 x86_64
Build options :
TARGET = linux-glibc
CPU = generic
CC = cc
CFLAGS = -m64 -march=x86-64 -O2 -g -Wall -Wextra -Wundef -Wdeclaration-after-statement -Wfatal-errors -Wtype-limits -Wshift-negative-value -Wshift-overflow=2 -Wduplicated-cond -Wnull-dereference -fwrapv -Wno-address-of-packed-member -Wno-unused-label -Wno-sign-compare -Wno-unused-parameter -Wno-clobbered -Wno-missing-field-initializers -Wno-cast-function-type -Wno-string-plus-int -Wno-atomic-alignment
OPTIONS = USE_OPENSSL=1 USE_LUA=1 USE_ZLIB=1 USE_CPU_AFFINITY=1 USE_SYSTEMD=1 USE_PCRE=1
DEBUG = -DDEBUG_STRICT -DDEBUG_MEMORY_POOLS
Feature list : -51DEGREES +ACCEPT4 +BACKTRACE -CLOSEFROM +CPU_AFFINITY +CRYPT_H -DEVICEATLAS +DL -ENGINE +EPOLL -EVPORTS +GETADDRINFO -KQUEUE -LIBATOMIC +LIBCRYPT +LINUX_CAP +LINUX_SPLICE +LINUX_TPROXY +LUA +MATH -MEMORY_PROFILING +NETFILTER +NS -OBSOLETE_LINKER +OPENSSL -OPENSSL_WOLFSSL -OT +PCRE -PCRE2 -PCRE2_JIT -PCRE_JIT +POLL +PRCTL -PROCCTL -PROMEX -PTHREAD_EMULATION -QUIC -QUIC_OPENSSL_COMPAT +RT +SHM_OPEN -SLZ +SSL -STATIC_PCRE -STATIC_PCRE2 +SYSTEMD +TFO +THREAD +THREAD_DUMP +TPROXY -WURFL +ZLIB
Default settings :
bufsize = 16384, maxrewrite = 1024, maxpollevents = 200
Built with multi-threading support (MAX_TGROUPS=16, MAX_THREADS=256, default=2).
Built with OpenSSL version : OpenSSL 3.0.7 1 Nov 2022
Running on OpenSSL version : OpenSSL 3.0.7 1 Nov 2022
OpenSSL library supports TLS extensions : yes
OpenSSL library supports SNI : yes
OpenSSL library supports : TLSv1.0 TLSv1.1 TLSv1.2 TLSv1.3
OpenSSL providers loaded : default
Built with Lua version : Lua 5.4.6
Built with network namespace support.
Built with zlib version : 1.2.11
Running on zlib version : 1.2.11
Compression algorithms supported : identity("identity"), deflate("deflate"), raw-deflate("deflate"), gzip("gzip")
Built with transparent proxy support using: IP_TRANSPARENT IPV6_TRANSPARENT IP_FREEBIND
Built with PCRE version : 8.44 2020-02-12
Running on PCRE version : 8.44 2020-02-12
PCRE library supports JIT : no (USE_PCRE_JIT not set)
Encrypted password support via crypt(3): yes
Built with gcc compiler version 11.4.1 20230605 (Red Hat 11.4.1-2)
Available polling systems :
epoll : pref=300, test result OK
poll : pref=200, test result OK
select : pref=150, test result OK
Total: 3 (3 usable), will use epoll.
Available multiplexer protocols :
(protocols marked as <default> cannot be specified using 'proto' keyword)
h2 : mode=HTTP side=FE|BE mux=H2 flags=HTX|HOL_RISK|NO_UPG
fcgi : mode=HTTP side=BE mux=FCGI flags=HTX|HOL_RISK|NO_UPG
<default> : mode=HTTP side=FE|BE mux=H1 flags=HTX
h1 : mode=HTTP side=FE|BE mux=H1 flags=HTX|NO_UPG
<default> : mode=TCP side=FE|BE mux=PASS flags=
none : mode=TCP side=FE|BE mux=PASS flags=NO_UPG
Available services : none
Available filters :
[BWLIM] bwlim-in
[BWLIM] bwlim-out
[CACHE] cache
[COMP] compression
[FCGI] fcgi-app
[SPOE] spoe
[TRACE] trace
# 默认缺少配置文件,无法启动
[root@rocky9-2 ~]# systemctl daemon-reload
[root@rocky9-2 ~]# systemctl start haproxy
Failed to start haproxy.service: Unit haproxy.service not found.
# 提示没有“haproxy.service”文件
# 创建service文件
[root@rocky9-2 ~]# cat > /lib/systemd/system/haproxy.service <<-EOF
[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target
[Service]
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID
[Install]
WantedBy=multi-user.target
EOF
[root@rocky9-2 ~]# tree /usr/local/src/haproxy-2.8.5/examples/
/usr/local/src/haproxy-2.8.5/examples/
├── basic-config-edge.cfg
├── content-sw-sample.cfg
├── errorfiles
│ ├── 400.http
│ ├── 403.http
│ ├── 408.http
│ ├── 500.http
│ ├── 502.http
│ ├── 503.http
│ ├── 504.http
│ └── README
├── haproxy.init
├── lua
│ ├── event_handler.lua
│ ├── mailers.lua
│ └── README
├── option-http_proxy.cfg
├── quick-test.cfg
├── socks4.cfg
├── transparent_proxy.cfg
└── wurfl-example.cfg
2 directories, 19 files
# examples目录下有默认的配置文件,可以直接把“quick-test.cfg”文件复制过去
# 这里我们创建自定义的配置文件
[root@rocky9-2 ~]# mkdir /etc/haproxy
[root@rocky9-2 ~]# cat > /etc/haproxy/haproxy.cfg <<-EOF
global
maxconn 100000
chroot /apps/haproxy
stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
user haproxy
group haproxy
daemon
pidfile /var/lib/haproxy/haproxy.pid
log 127.0.0.1 local2 info
defaults
option http-keep-alive
option forwardfor
maxconn 100000
mode http
timeout connect 300000ms
timeout client 300000ms
timeout server 300000ms
listen stats
mode http
bind 0.0.0.0:9999
stats enable
log global
stats uri /haproxy-status
stats auth haadmin:123456
listen web_port
bind 172.31.0.19:80
mode http
log global
server web1 127.0.0.1:8080 check inter 3000 fall 2 rise 5
EOF
HAProxy 的配置文件haproxy.cfg由两大部分组成,分别是global和proxies部分
[root@rocky9-2 ~]# cat /etc/haproxy/haproxy.cfg
global # global 配置参数
maxconn 100000 # 每个haproxy进程的最大并发连接数
chroot /apps/haproxy # 锁定运行目录
stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin #socket文件,并可以通过此文件管理
user haproxy # user, group是运行haproxy的用户身份
group haproxy
daemon # 以守护进程运行
pidfile /var/lib/haproxy/haproxy.pid # 指定pid文件路径
log 127.0.0.1 local2 info # 定义全局的syslog服务器;日志服务器需要开启UDP协议,最多可以定义两
# proxies:代理配置段
defaults # Proxies配置-defaults
option http-keep-alive # 开启与客户端的会话保持
option forwardfor # 透传客户端真实IP至后端web服务器
maxconn 100000 # 每个haproxy进程的最大并发连接数
mode http # 设置默认工作类型
timeout connect 300000ms # 客户端请求从haproxy到后端server最长连接等待时间(TCP连接之前),默认单位ms
timeout client 300000ms # 设置haproxy与客户端的最长非活动时间,默认单位ms,建议和timeout server相同
timeout server 300000ms # 客户端请求从haproxy到后端服务端的请求处理超时时长(TCP连接之后),默认单位ms,如果超时,会出现502错误,此值建议设置较大些,防止出现502错误
listen stats # 状态页配置项
mode http # 设置默认工作类型
bind 0.0.0.0:9999 # 指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字段中
stats enable # 基于默认的参数启用stats page
log global # 开启当前状态页的日志功能,默认不记录日志
stats uri /haproxy-status # 自定义stats page uri
stats auth haadmin:123456 # 认证时的账号和密码,可定义多个用户,每行指定一个用户.默认:no authentication
listen web_port # Proxies配置-listen
bind 172.31.0.19:80 # 指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字段中
mode http # 指定负载协议类型
log global # 开启当前web_port的日志功能,默认不记录日志
#balance roundrobin # balance是haproxy的算法,roundrobin为默认调度算法,基于权重的轮询动态调度算法,支持权重的运行时调整,如果不写就是默认的
#balance source # 源地址hash,基于用户源地址hash并将请求转发到后端服务器,后续同一个源地址请求将被转发至同一个后端web服务器。此方式当后端服务器数据量发生变化时,会导致很多用户的请求转发至新的后端服务器,默认为静态方式,但是可以通过hash-type选项进行更改,在harbor高可用的时候要配置balance source
server web1 127.0.0.1:8080 check inter 3000 fall 2 rise 5 # server配置,
# check 对指定real进行健康状态检查,如果不加此设置,默认不开启检查,只有check后面没有其它配置也可以启用检查功能;默认对相应的后端服务器IP和端口,利用TCP连接进行周期性健康性检查,注意必须指定端口才能实现健康性检查;
# inter 健康状态检查间隔时间,默认2000 ms;
# fall 后端服务器从线上转为线下的检查的连续失效次数,默认为3;
# rise 后端服务器从下线恢复上线的检查的连续有效次数,默认为2。
# 注意:如果需要绑定在非本机的IP,需要开启内核参数:net.ipv4.ip_nonlocal_bind=1
[root@rocky9-2 ~]# cat >> /etc/sysctl.conf <<-EOF
net.ipv4.ip_nonlocal_bind = 1
EOF
[root@rocky9-2 ~]# sysctl -p
# 准备socket文件目录
[root@rocky9-2 ~]# mkdir -p /var/lib/haproxy/
# 设置用户和目录权限
[root@rocky9-2 ~]# useradd -r -s /sbin/nologin -d /var/lib/haproxy haproxy
[root@rocky9-2 ~]# systemctl daemon-reload && systemctl enable --now haproxy
haproxy.cfg文件中定义了chroot、pidfile、user、group等参数,如果系统没有相应的资源会导致haproxy无法启动,具体参考日志文件/var/log/messages
[root@rocky9-2 ~]# systemctl status haproxy
● haproxy.service - HAProxy Load Balancer
Loaded: loaded (/usr/lib/systemd/system/haproxy.service; enabled; preset: disabled)
Active: active (running) since Sat 2024-01-27 22:31:45 CST; 2min 38s ago
Process: 21423 ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q (code=exited, status=0/SUCCESS)
Main PID: 21425 (haproxy)
Tasks: 3 (limit: 10840)
Memory: 21.5M
CPU: 41ms
CGroup: /system.slice/haproxy.service
├─21425 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
└─21427 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
Jan 27 22:31:45 rocky9-2 systemd[1]: Starting HAProxy Load Balancer...
Jan 27 22:31:45 rocky9-2 systemd[1]: Started HAProxy Load Balancer.
Jan 27 22:31:45 rocky9-2 haproxy[21425]: [NOTICE] (21425) : haproxy version is 2.8.5-aaba8d0
Jan 27 22:31:45 rocky9-2 haproxy[21425]: [NOTICE] (21425) : path to executable is /usr/sbin/haproxy
Jan 27 22:31:45 rocky9-2 haproxy[21425]: [ALERT] (21425) : config : parsing [/etc/haproxy/haproxy.cfg:15] : 'pidfile>
Jan 27 22:31:45 rocky9-2 haproxy[21425]: [NOTICE] (21425) : New worker (21427) forked
Jan 27 22:31:45 rocky9-2 haproxy[21425]: [NOTICE] (21425) : Loading success.
Jan 27 22:31:45 rocky9-2 haproxy[21427]: [WARNING] (21427) : Server web_port/web1 is DOWN, reason: Layer4 connection p>
Jan 27 22:31:45 rocky9-2 haproxy[21427]: [ALERT] (21427) : proxy 'web_port' has no server available!
[root@rocky9-2 ~]# pstree -p |grep haproxy
|-haproxy(21425)---haproxy(21427)---{haproxy}(21428)
浏览器访问: http://172.31.0.9:9999/haproxy-status,输入用户名和密码登录。
图1-7 登录haproxy状态页面
图1-8 haproxy状态页面
Shell脚本源码地址:
Gitee:https://gitee.com/raymond9/shell
Github:https://github.com/raymond999999/shell
可以去上面的Gitee或Github代码仓库拉取脚本。
[root@rocky9-2 ~]# cat install_haproxy_v2.sh
#!/bin/bash
#
#************************************************************************************************************
#Author: Raymond
#QQ: 88563128
#Date: 2024-01-30
#FileName: install_haproxy_v2.sh
#URL: raymond.blog.csdn.net
#Description: install_haproxy for CentOS 7 & CentOS Stream 8/9 & Ubuntu 18.04/20.04/22.04 & Rocky 8/9
#Copyright (C): 2024 All rights reserved
#************************************************************************************************************
SRC_DIR=/usr/local/src
COLOR="echo -e \\033[01;31m"
END='\033[0m'
CPUS=`lscpu |awk '/^CPU\(s\)/{print $2}'`
#lua下载地址:”https://www.lua.org/ftp/lua-5.4.6.tar.gz“,请提前下载。
LUA_FILE=lua-5.4.6.tar.gz
#haproxy下载地址:“https://www.haproxy.org/download/2.8/src/haproxy-2.8.5.tar.gz”,请提前下载。
HAPROXY_FILE=haproxy-2.8.5.tar.gz
HAPROXY_INSTALL_DIR=/apps/haproxy
STATS_AUTH_USER=admin
STATS_AUTH_PASSWORD=123456
NET_NAME=`ip addr |awk -F"[: ]" '/^2: e.*/{print $3}'`
IP=`ip addr show ${NET_NAME}| awk -F" +|/" '/global/{print $3}'`
os(){
OS_ID=`sed -rn '/^NAME=/s@.*="([[:alpha:]]+).*"$@\1@p' /etc/os-release`
}
check_file (){
cd ${SRC_DIR}
${COLOR}'检查Haproxy相关源码包'${END}
if [ ! -e ${LUA_FILE} ];then
${COLOR}"缺少${LUA_FILE}文件,请把文件放到${SRC_DIR}目录下"${END}
exit
elif [ ! -e ${HAPROXY_FILE} ];then
${COLOR}"缺少${HAPROXY_FILE}文件,请把文件放到${SRC_DIR}目录下"${END}
exit
else
${COLOR}"相关文件已准备好"${END}
fi
}
install_haproxy(){
[ -d ${HAPROXY_INSTALL_DIR} ] && { ${COLOR}"Haproxy已存在,安装失败"${END};exit; }
${COLOR}"开始安装Haproxy"${END}
${COLOR}"开始安装Haproxy依赖包"${END}
if [ ${OS_ID} == "CentOS" -o ${OS_ID} == "Rocky" ] &> /dev/null;then
yum -y install gcc make readline-devel openssl-devel pcre-devel systemd-devel zlib-devel &> /dev/null
else
apt update &> /dev/null;apt -y install gcc make libreadline-dev openssl libssl-dev libpcre3 libpcre3-dev zlib1g-dev libsystemd-dev &> /dev/null
fi
if [ ${OS_ID} == "CentOS" -o ${OS_ID} == "Rocky" ] &> /dev/null;then
rpm -q tar &> /dev/null || { ${COLOR}"安装tar工具,请稍等..."${END};yum -y install tar &> /dev/null; }
fi
tar xf ${LUA_FILE}
LUA_DIR=`echo ${LUA_FILE} | sed -nr 's/^(.*[0-9]).([[:lower:]]).*/\1/p'`
cd ${LUA_DIR}
make linux test
cd ${SRC_DIR}
tar xf ${HAPROXY_FILE}
HAPROXY_DIR=`echo ${HAPROXY_FILE} | sed -nr 's/^(.*[0-9]).([[:lower:]]).*/\1/p'`
cd ${HAPROXY_DIR}
make -j ${CPUS} ARCH=x86_64 TARGET=linux-glibc USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_CPU_AFFINITY=1 USE_LUA=1 LUA_INC=${SRC_DIR}/${LUA_DIR}/src/ LUA_LIB=${SRC_DIR}/${LUA_DIR}/src/
make install PREFIX=${HAPROXY_INSTALL_DIR}
[ $? -eq 0 ] && $COLOR"Haproxy编译安装成功"$END || { $COLOR"Haproxy编译安装失败,退出!"$END;exit; }
[ -L /usr/sbin/haproxy ] || ln -s ../..${HAPROXY_INSTALL_DIR}/sbin/haproxy /usr/sbin/ &> /dev/null
cat > /lib/systemd/system/haproxy.service <<-EOF
[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target
[Service]
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID
[Install]
WantedBy=multi-user.target
EOF
[ -d /etc/haproxy ] || mkdir /etc/haproxy &> /dev/null
cat > /etc/haproxy/haproxy.cfg <<-EOF
global
maxconn 100000
chroot ${HAPROXY_INSTALL_DIR}
stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
user haproxy
group haproxy
daemon
pidfile /var/lib/haproxy/haproxy.pid
log 127.0.0.1 local2 info
defaults
option http-keep-alive
option forwardfor
maxconn 100000
mode http
timeout connect 300000ms
timeout client 300000ms
timeout server 300000ms
listen stats
mode http
bind 0.0.0.0:9999
stats enable
log global
stats uri /haproxy-status
stats auth ${STATS_AUTH_USER}:${STATS_AUTH_PASSWORD}
listen web_port
bind ${IP}:80
mode http
log global
server web1 127.0.0.1:8080 check inter 3000 fall 2 rise 5
EOF
cat >> /etc/sysctl.conf <<-EOF
net.ipv4.ip_nonlocal_bind = 1
EOF
sysctl -p &> /dev/null
[ -d /var/lib/haproxy/ ] || mkdir -p /var/lib/haproxy/ &> /dev/null
echo "PATH=${HAPROXY_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/haproxy.sh
useradd -r -s /sbin/nologin -d /var/lib/haproxy haproxy
systemctl daemon-reload
systemctl enable --now haproxy &> /dev/null
systemctl is-active haproxy &> /dev/null && ${COLOR}"Haproxy 服务启动成功!"${END} || { ${COLOR}"Haproxy 启动失败,退出!"${END} ; exit; }
${COLOR}"Haproxy安装完成"${END}
}
main(){
os
check_file
install_haproxy
}
main
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。