HAProxy ist der Industriestandard für High-Performance Load Balancing. Erweiterte Features wie ACLs, Stick Tables und Health Checks ermöglichen komplexe Szenarien.
ACLs (Access Control Lists)
Grundlegende ACLs
frontend http_front
bind *:80
# Pfad-basierte ACLs
acl is_api path_beg /api
acl is_static path_end .css .js .png .jpg .gif
acl is_admin path_beg /admin
# Host-basierte ACLs
acl host_api hdr(host) -i api.example.com
acl host_www hdr(host) -i www.example.com
# IP-basierte ACLs
acl internal_network src 192.168.0.0/16 10.0.0.0/8
acl blocked_ips src 1.2.3.4 5.6.7.8
# Header-basierte ACLs
acl is_mobile hdr_sub(User-Agent) -i mobile android iphone
acl has_auth_header hdr(Authorization) -m found
# Routing-Entscheidungen
use_backend api_servers if is_api
use_backend static_servers if is_static
use_backend admin_servers if is_admin internal_network
# Block
http-request deny if blocked_ips
default_backend web_serversACL-Flags
| Flag | Beschreibung | |------|--------------| | -i | Case-insensitive | | -m | Match-Methode | | -f | Aus Datei lesen | | -u | Unique ID |
Match-Methoden
# Exakt
acl exact_match path -m str /exact/path
# Prefix
acl prefix_match path -m beg /api
# Suffix
acl suffix_match path -m end .php
# Regex
acl regex_match path -m reg ^/user/[0-9]+$
# Substring
acl substr_match hdr(User-Agent) -m sub Chrome
# Domain
acl domain_match hdr(host) -m dom example.comStick Tables
Session Persistence
backend web_servers
balance roundrobin
# Stick Table definieren
stick-table type ip size 1m expire 30m
stick on src
server web1 192.168.1.10:80 check
server web2 192.168.1.11:80 check
server web3 192.168.1.12:80 checkCookie-basierte Persistenz
backend web_servers
balance roundrobin
cookie SERVERID insert indirect nocache
server web1 192.168.1.10:80 check cookie web1
server web2 192.168.1.11:80 check cookie web2
server web3 192.168.1.12:80 check cookie web3Rate Limiting mit Stick Tables
frontend http_front
bind *:80
# Stick Table für Rate Limiting
stick-table type ip size 100k expire 30s store http_req_rate(10s)
# Requests tracken
http-request track-sc0 src
# Rate Limit: Max 100 Requests/10s
acl rate_abuse sc_http_req_rate(0) gt 100
http-request deny deny_status 429 if rate_abuseVerbindungs-Tracking
frontend http_front
bind *:80
stick-table type ip size 100k expire 1m store conn_cur,conn_rate(10s),http_req_rate(10s),http_err_rate(10s)
http-request track-sc0 src
# Zu viele gleichzeitige Verbindungen
acl too_many_conns sc_conn_cur(0) gt 50
# Zu viele Requests
acl too_many_requests sc_http_req_rate(0) gt 100
# Zu viele Fehler (Bot/Scraper)
acl too_many_errors sc_http_err_rate(0) gt 20
http-request deny deny_status 429 if too_many_conns || too_many_requests
http-request deny deny_status 403 if too_many_errorsHealth Checks
HTTP Health Check
backend web_servers
balance roundrobin
option httpchk GET /health HTTP/1.1\r\nHost:\ localhost
http-check expect status 200
server web1 192.168.1.10:80 check inter 5s fall 3 rise 2
server web2 192.168.1.11:80 check inter 5s fall 3 rise 2Erweiterte Health Checks
backend api_servers
balance roundrobin
option httpchk
http-check connect
http-check send meth GET uri /api/health ver HTTP/1.1 hdr Host localhost
http-check expect status 200
http-check expect string "healthy"
server api1 192.168.1.20:8080 check
server api2 192.168.1.21:8080 checkMySQL Health Check
backend mysql_servers
mode tcp
option mysql-check user haproxy_check
server mysql1 192.168.1.30:3306 check
server mysql2 192.168.1.31:3306 check backupRedis Health Check
backend redis_servers
mode tcp
option tcp-check
tcp-check send PING\r\n
tcp-check expect string +PONG
server redis1 192.168.1.40:6379 check
server redis2 192.168.1.41:6379 checkSSL/TLS
SSL Termination
frontend https_front
bind *:443 ssl crt /etc/haproxy/certs/
# HSTS
http-response set-header Strict-Transport-Security "max-age=31536000"
# HTTP zu HTTPS Redirect
http-request redirect scheme https unless { ssl_fc }
default_backend web_serversSSL Passthrough
frontend https_passthrough
bind *:443
mode tcp
# SNI-basiertes Routing
tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }
acl is_api req_ssl_sni -i api.example.com
use_backend api_ssl if is_api
default_backend web_ssl
backend web_ssl
mode tcp
server web1 192.168.1.10:443 checkClient Certificate Auth
frontend https_front
bind *:443 ssl crt /etc/haproxy/certs/server.pem ca-file /etc/haproxy/certs/ca.pem verify required
# Client CN extrahieren
http-request set-header X-Client-CN %{+Q}[ssl_c_s_dn(cn)]
default_backend secure_serversKompression
frontend http_front
bind *:80
compression algo gzip
compression type text/html text/plain text/css application/javascript application/json
default_backend web_serversRequest/Response Manipulation
Header-Manipulation
frontend http_front
bind *:80
# Request Header hinzufügen
http-request set-header X-Forwarded-Proto http
http-request set-header X-Real-IP %[src]
# Header entfernen
http-request del-header X-Debug
# Response Header
http-response set-header X-Frame-Options DENY
http-response set-header X-Content-Type-Options nosniff
http-response del-header ServerURL Rewriting
frontend http_front
bind *:80
# Pfad umschreiben
http-request set-path /api/v2%[path] if { path_beg /api/v1 }
# Query String hinzufügen
http-request set-query %[query]&source=haproxy if { path_beg /track }Redirects
frontend http_front
bind *:80
# Permanent Redirect
http-request redirect prefix https://www.example.com code 301 if !{ hdr(host) -i www.example.com }
# Temporary Redirect
http-request redirect location /maintenance.html code 302 if { path / } { env(MAINTENANCE) -m bool }Logging
Erweitertes Logging
global
log /dev/log local0
log /dev/log local1 notice
defaults
log global
option httplog
option dontlognull
frontend http_front
# Custom Log Format
log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %CC %CS %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq %hr %hs %{+Q}r"Log-Format-Variablen
| Variable | Beschreibung | |----------|--------------| | %ci | Client IP | | %cp | Client Port | | %ST | Status Code | | %B | Bytes sent | | %Tr | Response Time | | %r | Request |
Stats und Monitoring
Stats Page
frontend stats
bind *:8404
mode http
stats enable
stats uri /stats
stats refresh 10s
stats auth admin:password
stats admin if TRUEPrometheus Metrics
frontend prometheus
bind *:8405
mode http
http-request use-service prometheus-exporter if { path /metrics }Runtime API
global
stats socket /var/run/haproxy/admin.sock mode 660 level admin
stats timeout 30s# Server deaktivieren
echo "disable server web_servers/web1" | socat stdio /var/run/haproxy/admin.sock
# Gewicht ändern
echo "set server web_servers/web1 weight 50" | socat stdio /var/run/haproxy/admin.sock
# Info abfragen
echo "show stat" | socat stdio /var/run/haproxy/admin.sockHochverfügbarkeit
Keepalived Integration
# /etc/keepalived/keepalived.conf
vrrp_script chk_haproxy {
script "killall -0 haproxy"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 101
virtual_ipaddress {
192.168.1.100/24
}
track_script {
chk_haproxy
}
}Peer Sync
peers mypeers
peer haproxy1 192.168.1.1:1024
peer haproxy2 192.168.1.2:1024
backend web_servers
stick-table type ip size 1m expire 30m peers mypeers
stick on srcVollständige Beispielkonfiguration
global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
stats socket /var/run/haproxy/admin.sock mode 660 level admin
stats timeout 30s
user haproxy
group haproxy
daemon
maxconn 50000
defaults
log global
mode http
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
timeout connect 5s
timeout client 50s
timeout server 50s
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
frontend http_front
bind *:80
bind *:443 ssl crt /etc/haproxy/certs/
# Rate Limiting
stick-table type ip size 100k expire 30s store http_req_rate(10s)
http-request track-sc0 src
http-request deny deny_status 429 if { sc_http_req_rate(0) gt 100 }
# ACLs
acl is_api path_beg /api
acl is_websocket hdr(Upgrade) -i websocket
# Headers
http-response set-header X-Frame-Options DENY
http-response del-header Server
use_backend api_servers if is_api
use_backend websocket_servers if is_websocket
default_backend web_servers
backend web_servers
balance roundrobin
option httpchk GET /health
http-check expect status 200
cookie SERVERID insert indirect nocache
server web1 192.168.1.10:80 check cookie web1
server web2 192.168.1.11:80 check cookie web2
server web3 192.168.1.12:80 check cookie web3
backend api_servers
balance leastconn
option httpchk GET /api/health
server api1 192.168.1.20:8080 check
server api2 192.168.1.21:8080 check
backend websocket_servers
balance source
option http-server-close
timeout tunnel 1h
server ws1 192.168.1.30:8080 check
server ws2 192.168.1.31:8080 checkZusammenfassung
| Feature | Verwendung | |---------|------------| | ACLs | Routing-Entscheidungen | | Stick Tables | Session Persistence, Rate Limiting | | Health Checks | Server-Überwachung | | SSL Termination | HTTPS-Verarbeitung | | Runtime API | Live-Konfiguration |
| Befehl | Funktion | |--------|----------| | http-request deny | Request blockieren | | use_backend | Backend wählen | | stick on | Session-Binding | | option httpchk | Health Check |
Fazit
HAProxy bietet mit ACLs und Stick Tables mächtige Werkzeuge für komplexe Load-Balancing-Szenarien. Die Kombination aus Rate Limiting, Health Checks und Session Persistence ermöglicht robuste Hochverfügbarkeits-Setups. Die Runtime API erlaubt Änderungen ohne Neustart. Für Enterprise-Anwendungen ist HAProxy oft die beste Wahl.