skip to content

Recherche

HAProxy

Load balancer HAProxy - configuration, backend et monitoring haute performance !

HAProxy est un load balancer et proxy server open source conçu pour la haute disponibilité, la répartition de charge et le proxy pour les applications TCP et HTTP.

⚙️ Gestion du service

📌 Action🧠 Commande
▶️ Démarrer HAProxysudo systemctl start haproxy
⏹️ Arrêter HAProxysudo systemctl stop haproxy
🔁 Redémarrer HAProxysudo systemctl restart haproxy
🔄 Recharger la configsudo systemctl reload haproxy
📊 Statut du servicesudo systemctl status haproxy
🚀 Activer au démarragesudo systemctl enable haproxy
✅ Tester la configurationsudo haproxy -f /etc/haproxy/haproxy.cfg -c
📋 Version d’HAProxyhaproxy -v

📂 Configuration

📌 Fichier/Dossier🧠 Description
/etc/haproxy/haproxy.cfgConfiguration principale
/var/log/haproxy.logLogs HAProxy
/var/lib/haproxy/statsSocket de statistiques
/etc/default/haproxyConfiguration du service
/etc/rsyslog.confConfiguration des logs système

🏗️ Structure de configuration

Sections principales

📌 Section🧠 Description📊 Utilisation
globalConfiguration globaleProcessus, logs, sécurité
defaultsParamètres par défautTimeouts, mode, options
frontendPoint d’entrée des requêtesÉcoute, routage
backendServeurs de destinationLoad balancing, santé
listenFrontend + Backend combinésConfiguration simple

📝 Configuration basique

Configuration HTTP simple

global
    daemon
    user haproxy
    group haproxy
    chroot /var/lib/haproxy
    stats socket /var/run/haproxy.sock mode 660
 
defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms
 
frontend web_frontend
    bind *:80
    default_backend web_servers
 
backend web_servers
    balance roundrobin
    server web1 192.168.1.10:8080 check
    server web2 192.168.1.11:8080 check
    server web3 192.168.1.12:8080 check

Configuration HTTPS avec SSL

frontend https_frontend
    bind *:443 ssl crt /etc/ssl/certs/example.pem
    redirect scheme https if !{ ssl_fc }
    default_backend web_servers
 
backend web_servers
    balance roundrobin
    option httpchk GET /health
    server web1 192.168.1.10:8080 check
    server web2 192.168.1.11:8080 check backup

⚖️ Algorithmes de load balancing

📌 Algorithme🧠 Description📊 Configuration
roundrobinRotation circulairebalance roundrobin
leastconnMoins de connexionsbalance leastconn
sourceHash sur IP sourcebalance source
uriHash sur URIbalance uri
url_paramHash sur paramètre URLbalance url_param id
randomSélection aléatoirebalance random
firstPremier serveur disponiblebalance first

Exemples de configuration

# Load balancing par IP source (session sticky)
backend api_servers
    balance source
    hash-type consistent
    server api1 10.0.1.10:3000 check
    server api2 10.0.1.11:3000 check
 
# Load balancing par URI
backend static_servers
    balance uri whole
    server static1 10.0.2.10:80 check
    server static2 10.0.2.11:80 check

🔍 Health checks et monitoring

📌 Check Type🧠 Configuration📊 Exemple
TCP simplecheckserver web1 ip:port check
HTTP GEToption httpchk GET /pathoption httpchk GET /health
HTTP avec headersoption httpchk GET /path HTTP/1.1\r\nHost:\ domainHeaders personnalisés
Interval checkcheck inter 5sVérif toutes les 5s
Retry countcheck rise 2 fall 32 OK pour UP, 3 KO pour DOWN

Configuration avancée des checks

backend app_servers
    option httpchk GET /api/health HTTP/1.1\r\nHost:\ api.example.com
    server app1 10.0.1.10:3000 check inter 10s rise 2 fall 3
    server app2 10.0.1.11:3000 check inter 10s rise 2 fall 3
    server app3 10.0.1.12:3000 check inter 10s rise 2 fall 3 backup

📊 Interface de statistiques

Configuration des stats

# Dans le frontend ou comme section listen
listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 30s
    stats admin if TRUE
    stats auth admin:password123

Accès aux statistiques

📌 Action🧠 URL/Commande
🌐 Interface webhttp://server:8404/stats
📊 Statistiques JSONhttp://server:8404/stats?stats;json
❌ Désactiver un serveurWeb UI ou echo "disable server backend/server1" | socat stdio /var/run/haproxy.sock
✅ Activer un serveurecho "enable server backend/server1" | socat stdio /var/run/haproxy.sock
📈 Statistiques temps réelecho "show stat" | socat stdio /var/run/haproxy.sock

🔧 Configuration avancée

SSL/TLS et sécurité

global
    ssl-default-bind-ciphers ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20:!aNULL:!SHA1:!AESCCM
    ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
 
frontend https_frontend
    bind *:443 ssl crt /etc/ssl/certs/ alpn h2,http/1.1
    
    # Security headers
    http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains"
    http-response set-header X-Frame-Options "DENY"
    http-response set-header X-Content-Type-Options "nosniff"
    
    # Redirection HTTPS
    redirect scheme https if !{ ssl_fc }

Routage basé sur le contenu

frontend web_frontend
    bind *:80
    
    # ACLs pour le routage
    acl is_api path_beg /api/
    acl is_static path_beg /static/
    acl is_admin hdr(host) -i admin.example.com
    
    # Routage conditionnel
    use_backend api_servers if is_api
    use_backend static_servers if is_static
    use_backend admin_servers if is_admin
    default_backend web_servers

Limitation de taux

# Limitation globale
frontend web_frontend
    stick-table type ip size 100k expire 30s store http_req_rate(10s)
    http-request track-sc0 src
    http-request deny if { sc_http_req_rate(0) gt 20 }

📜 Logs et monitoring

📌 Action🧠 Configuration/Commande
📊 Activer les logs HTTPoption httplog
🔍 Logs détaillés TCPoption tcplog
📝 Logs vers sysloglog 127.0.0.1:514 local0
📈 Voir logs en temps réelsudo tail -f /var/log/haproxy.log
📊 Statistiques via socketecho "show info" | socat stdio /var/run/haproxy.sock
🔍 État des serveursecho "show servers state" | socat stdio /var/run/haproxy.sock

Configuration des logs

global
    log 127.0.0.1:514 local0 info
    chroot /var/lib/haproxy
    user haproxy
    group haproxy
 
defaults
    log global
    option httplog
    option dontlognull
    option log-health-checks

🛠️ Dépannage courant

🆘 Problème🧠 Solution
❌ Erreur de configurationhaproxy -f /etc/haproxy/haproxy.cfg -c
🔧 Service ne démarre pasVérifier syntaxe et permissions
📡 Backend inaccessibleVérifier health checks et connectivité
🐌 Performance dégradéeAjuster timeouts et algorithme LB
📊 Stats inaccessiblesVérifier bind et auth des stats
🔒 Problèmes SSLVérifier certificats et chemins

🎯 Commandes de gestion

📌 Action🧠 Commande
📊 Statistiques généralesecho "show info" | socat stdio /var/run/haproxy.sock
🔍 État des backendsecho "show stat" | socat stdio /var/run/haproxy.sock
❌ Désactiver serveurecho "disable server backend/server1" | socat stdio /var/run/haproxy.sock
✅ Activer serveurecho "enable server backend/server1" | socat stdio /var/run/haproxy.sock
🔧 Changer poids serveurecho "set weight backend/server1 50%" | socat stdio /var/run/haproxy.sock
📋 Sessions activesecho "show sess" | socat stdio /var/run/haproxy.sock
🗑️ Vider sessionsecho "clear counters all" | socat stdio /var/run/haproxy.sock

🎯 Conseils pratiques

Bonnes pratiques

  • ✅ Toujours tester la config : haproxy -f /etc/haproxy/haproxy.cfg -c
  • 📊 Surveiller les stats via l’interface web :8404/stats
  • 🔍 Activer les logs pour diagnostiquer les problèmes
  • ⚖️ Utiliser leastconn pour des charges variables
  • 🛡️ Configurer une whitelist pour les IPs admin