HAProxy是一款高性能的TCP/HTTP负载均衡器,广泛用于高可用性和负载均衡场景。以下是详细的配置步骤:
sudo apt update
sudo apt install haproxy
sudo yum install haproxy
wget http://www.haproxy.org/download/2.8/src/haproxy-2.8.3.tar.gz
tar -xzvf haproxy-2.8.3.tar.gz
cd haproxy-2.8.3
make TARGET=linux-glibc USE_OPENSSL=1 USE_ZLIB=1 USE_PCRE=1
sudo make install
编辑主配置文件(通常位于/etc/haproxy/haproxy.cfg
):
sudo nano /etc/haproxy/haproxy.cfg
global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
stats socket /run/haproxy/admin.sock mode 660 level admin
stats timeout 30s
user haproxy
group haproxy
daemon
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5000
timeout client 50000
timeout server 50000
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
frontend http_front
bind *:80
stats uri /haproxy?stats
default_backend http_back
backend http_back
balance roundrobin
server server1 192.168.1.101:80 check
server server2 192.168.1.102:80 check
server server3 192.168.1.103:80 check
backend http_back
balance roundrobin # 轮询(默认)
# balance leastconn # 最少连接
# balance source # 源IP哈希
# balance uri # URI哈希
frontend https_front
bind *:443 ssl crt /etc/ssl/private/example.com.pem
http-request redirect scheme https unless { ssl_fc }
default_backend http_back
backend http_back
option httpchk GET /health
http-check expect status 200
server server1 192.168.1.101:80 check inter 2000 rise 2 fall 3
backend http_back
cookie SERVERID insert indirect nocache
server server1 192.168.1.101:80 cookie s1 check
server server2 192.168.1.102:80 cookie s2 check
sudo systemctl start haproxy
sudo systemctl enable haproxy
sudo systemctl status haproxy
sudo systemctl reload haproxy
# 或
sudo haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -sf $(cat /run/haproxy.pid)
在浏览器中访问:http://your-haproxy-server/haproxy?stats
确保rsyslog配置中包含:
local0.* /var/log/haproxy.log
然后重启rsyslog:
sudo systemctl restart rsyslog
frontend stats
bind *:8404
stats enable
stats uri /stats
stats refresh 10s
stats auth admin:securepassword
acl network_allowed src 192.168.1.0/24
http-request deny unless network_allowed
userlist AuthUsers
user admin insecure-password yourpassword
acl restricted_page path_beg /admin
acl allowed_ips src 192.168.1.100 192.168.1.200
http-request deny if restricted_page !allowed_ips
maxconn 50000
echo "net.ipv4.tcp_max_syn_backlog = 10240" >> /etc/sysctl.conf
echo "net.core.somaxconn = 10240" >> /etc/sysctl.conf
sysctl -p
global
nbthread 4
通过以上配置,您可以在Linux系统上搭建一个高性能的软件负载均衡器,根据实际需求调整配置参数以获得最佳性能。