Aller au contenu

Déployer HAProxy 2.8 + keepalived sur un cluster Ubuntu 22.04 à 2 nœuds (prêt pour la production)

Monter une paire HA HAProxy 2.8 + keepalived durcie sur Ubuntu 22.04 — VIP flottante VRRP, backends L4/L7, socket de stats, sondes santé, rechargements validés.

Vous montez un cluster HAProxy à deux nœuds derrière une VIP flottante. Le premier test de bascule passe — vous débranchez le câble, keepalived migre la VIP, le trafic continue. Six mois plus tard, une mise à jour de noyau de routine redémarre le primaire, la VIP part vers le secondaire, et y reste pour toujours parce que personne n’a remarqué que unicast_peer n’a jamais été configuré, le cluster tournait sur du multicast que le réseau cloud a silencieusement coupé après la fenêtre de maintenance, et la priority sur les deux nœuds était à 100. La « paire HA » n’était qu’un seul nœud depuis des mois.

Ce qui se passe

Un déploiement HAProxy + keepalived en production demande plus que l’installation du paquet. VRRP doit utiliser unicast_peer (ou un vrai réseau capable de multicast — la plupart des VPC cloud ne le sont pas), la priority doit différer entre les deux nœuds, et le vrrp_script chk_haproxy doit rétrograder le primaire quand HAProxy lui-même est tombé (pas seulement quand le nœud est tombé). HAProxy a besoin de son socket de stats admin sur un socket Unix — jamais sur un port TCP ouvert au monde — avec level admin uniquement pour l’utilisateur de gestion local. Les sondes santé des backends doivent utiliser un vrai option httpchk GET /healthz HTTP/1.1 plutôt qu’une sonde TCP qui réussit contre n’importe quel écouteur. timeout connect, timeout client, timeout server et timeout queue doivent être réglés explicitement (HAProxy a un connect par défaut d’une seconde et aucun plafond de file). Et tout changement de config doit passer par haproxy -c -f avant systemctl reload haproxy — il n’y a pas de chemin « valider à l’application » ; une erreur de syntaxe descend l’écouteur.

Comment vérifier

Après installation, sur chaque nœud :

ss -lntp | grep -E ':(80|443|8404)\b'
# nœud-a : 10.0.0.10:80, 10.0.0.10:443, 127.0.0.1:8404
# nœud-b : 10.0.0.11:80, 10.0.0.11:443, 127.0.0.1:8404
# La VIP 10.0.0.50 doit apparaître uniquement sur le maître :
ip -4 addr show | grep '10.0.0.50'

Confirmez que keepalived voit son pair et que la bonne priorité est maître :

journalctl -u keepalived -n 50 --no-pager | grep -iE 'state|entering|backup|master'

Validez la syntaxe HAProxy avant tout rechargement :

haproxy -c -f /etc/haproxy/haproxy.cfg

Tapez sur le socket de stats depuis le nœud local pour confirmer qu’il s’agit d’un socket Unix et non d’un écouteur TCP :

echo "show info" | sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock | head -20
ss -lntp | grep 9000 || echo "pas de stats TCP — bon"

Si la VIP est sur les deux nœuds, que les deux processus keepalived rapportent MASTER, ou que haproxy -c -f retourne des erreurs, le cluster n’est pas prêt à supporter un redémarrage.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-haproxy-keepalived-ubuntu22.sh sur chaque nœud, puis exécutez-le. Il déroule l’installation complète sur une VM Ubuntu 22.04 fraîche : mise à jour de base, installe HAProxy 2.8 et keepalived depuis la PPA HAProxy, durcit SSH en gardant la clé root, configure ufw pour n’autoriser que 22/80/443 plus le VRRP multicast vers le pair sur le LAN, applique l’ajustement sysctl pertinent pour un répartiteur de charge L4/L7 haute-concurrence, écrit un squelette haproxy.cfg (un frontend HTTP avec HSTS, un frontend TCP, deux backends avec sondes santé HTTP, socket de stats sur /run/haproxy/admin.sock), écrit un keepalived.conf avec unicast_peer, un vrrp_script chk_haproxy, et les bons priority/state par nœud, monte LimitNOFILE à 200000 via un override systemd, valide la syntaxe HAProxy, et attend que les deux écouteurs du nœud local soient prêts avant de continuer.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 HAProxy 2.8 + keepalived HA installer
### Run on each node; export NODE_ROLE=master|backup and peer/VIP details first
### Stats socket on /run/haproxy/admin.sock (no TCP stats listener)
### No local backups; assumes VM-level backup
### Reboot remains manual

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

: "${NODE_ROLE:?Set NODE_ROLE=master or NODE_ROLE=backup}"
: "${NODE_IFACE:?Set NODE_IFACE=eth0 (the LAN interface)}"
: "${NODE_IP:?Set NODE_IP=10.0.0.10 (this node)}"
: "${PEER_IP:?Set PEER_IP=10.0.0.11 (the other node)}"
: "${VIP_CIDR:?Set VIP_CIDR=10.0.0.50/24 (floating VIP)}"
: "${VRRP_AUTH_PASS:?Set VRRP_AUTH_PASS=... (8-char shared secret)}"

if [[ "${NODE_ROLE}" == "master" ]]; then
  STATE="MASTER"
  PRIORITY=120
else
  STATE="BACKUP"
  PRIORITY=100
fi

echo
echo "========================================"
echo "HAProxy 2.8 + keepalived Setup (${NODE_ROLE})"
echo "========================================"
echo

echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade

echo "==> Installing base packages"
apt-get -y install \
  curl \
  ca-certificates \
  gnupg \
  software-properties-common \
  ufw \
  fail2ban \
  unattended-upgrades \
  chrony \
  lsof \
  socat \
  net-tools \
  jq

echo "==> Enabling time sync"
systemctl enable --now chrony
timedatectl set-ntp true

echo "==> Applying sysctl tuning for L4/L7 LB"
cat > /etc/sysctl.d/99-haproxy.conf <<'SYSCTL'
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 500000
net.ipv4.tcp_max_syn_backlog = 32768
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_max_tw_buckets = 1440000
net.ipv4.tcp_mem = 786432 1697152 1945728

net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr

net.ipv4.ip_nonlocal_bind = 1

net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

fs.file-max = 4194304
SYSCTL

modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system

echo "==> Setting file limits"
cat > /etc/security/limits.d/99-haproxy.conf <<'LIMITS'
* soft nofile 200000
* hard nofile 200000
root soft nofile 200000
root hard nofile 200000
haproxy soft nofile 200000
haproxy hard nofile 200000
LIMITS

echo "==> Hardening SSH while keeping root SSH key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)

set_sshd_option() {
  local key="$1"
  local value="$2"
  if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
  else
    echo "${key} ${value}" >> /etc/ssh/sshd_config
  fi
}

set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option ChallengeResponseAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4

sshd -t
systemctl restart ssh

echo "==> Configuring UFW (22/80/443 public, VRRP to peer only)"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow from "${PEER_IP}" to any port 112 proto any
ufw allow from "${PEER_IP}"
ufw --force enable

echo "==> Adding HAProxy 2.8 PPA"
add-apt-repository -y ppa:vbernat/haproxy-2.8
apt-get update
apt-get -y install haproxy=2.8.* keepalived

echo "==> Writing /etc/haproxy/haproxy.cfg"
mkdir -p /etc/haproxy /run/haproxy /var/log/haproxy
chown haproxy:haproxy /run/haproxy

cat > /etc/haproxy/haproxy.cfg <<'HAPROXY_CFG'
global
    log         /dev/log local0 info
    log         /dev/log local1 notice
    chroot      /var/lib/haproxy
    stats       socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
    stats       timeout 30s
    user        haproxy
    group       haproxy
    daemon
    maxconn     200000
    nbthread    4
    cpu-map     auto:1/1-4 0-3

    # Strong TLS defaults
    ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
    ssl-default-bind-ciphers      ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384
    ssl-default-bind-options      ssl-min-ver TLSv1.2 no-tls-tickets

defaults
    log         global
    mode        http
    option      httplog
    option      dontlognull
    option      http-server-close
    option      forwardfor
    option      redispatch
    retries     3
    timeout connect   5s
    timeout client    60s
    timeout server    60s
    timeout queue     10s
    timeout http-request 15s
    timeout http-keep-alive 10s

    # CommonLog-friendly capture for fail2ban
    log-format "%ci:%cp [%t] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %CC %CS %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq %hr %hs %{+Q}r"

frontend http_in
    bind *:80
    http-request redirect scheme https code 301 unless { ssl_fc }

frontend https_in
    bind *:443 ssl crt /etc/haproxy/certs/ alpn h2,http/1.1
    http-request set-header X-Real-IP %[src]
    http-request set-header X-Forwarded-Proto https
    http-request set-var(txn.req_id) uuid()
    http-request set-header X-Request-Id %[var(txn.req_id)]
    http-response set-header X-Request-Id %[var(txn.req_id)]
    http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains"
    http-response set-header X-Content-Type-Options nosniff
    http-response del-header Server

    acl is_api  path_beg /api/
    use_backend be_api  if is_api
    default_backend be_web

backend be_web
    balance     roundrobin
    option      httpchk GET /healthz HTTP/1.1\r\nHost:\ healthcheck
    http-check  expect status 200
    default-server inter 5s fall 3 rise 2 maxconn 1024
    server      web1 10.0.1.11:8080 check
    server      web2 10.0.1.12:8080 check

backend be_api
    balance     leastconn
    option      httpchk GET /api/healthz HTTP/1.1\r\nHost:\ healthcheck
    http-check  expect status 200
    default-server inter 5s fall 3 rise 2 maxconn 512
    server      api1 10.0.1.21:9000 check
    server      api2 10.0.1.22:9000 check
HAPROXY_CFG

# Cert directory (one PEM per site; production fills these in)
mkdir -p /etc/haproxy/certs
chmod 750 /etc/haproxy/certs
chown haproxy:haproxy /etc/haproxy/certs

echo "==> Validating HAProxy config syntax"
haproxy -c -f /etc/haproxy/haproxy.cfg

echo "==> Writing /etc/keepalived/keepalived.conf"
VIP_ADDR_ONLY="${VIP_CIDR%/*}"
cat > /etc/keepalived/keepalived.conf <<KA_CONF
global_defs {
    router_id ${NODE_ROLE^^}
    enable_script_security
    script_user root
}

vrrp_script chk_haproxy {
    script  "/usr/bin/pgrep -x haproxy"
    interval 2
    weight  -30
    fall    2
    rise    2
}

vrrp_instance VI_EDGE {
    state           ${STATE}
    interface       ${NODE_IFACE}
    virtual_router_id 51
    priority        ${PRIORITY}
    advert_int      1
    preempt_delay   30

    unicast_src_ip  ${NODE_IP}
    unicast_peer {
        ${PEER_IP}
    }

    authentication {
        auth_type PASS
        auth_pass ${VRRP_AUTH_PASS}
    }

    virtual_ipaddress {
        ${VIP_CIDR} dev ${NODE_IFACE}
    }

    track_script {
        chk_haproxy
    }

    notify_master "/usr/bin/logger keepalived: now MASTER (VIP ${VIP_ADDR_ONLY})"
    notify_backup "/usr/bin/logger keepalived: now BACKUP (VIP ${VIP_ADDR_ONLY})"
    notify_fault  "/usr/bin/logger keepalived: FAULT"
}
KA_CONF

chmod 600 /etc/keepalived/keepalived.conf

echo "==> Setting systemd limits for HAProxy"
mkdir -p /etc/systemd/system/haproxy.service.d
cat > /etc/systemd/system/haproxy.service.d/override.conf <<'HA_OVERRIDE'
[Service]
LimitNOFILE=200000
LimitNPROC=16384
HA_OVERRIDE

systemctl daemon-reload

echo "==> Configuring fail2ban for HAProxy log"
mkdir -p /etc/fail2ban/filter.d /etc/fail2ban/jail.d

cat > /etc/fail2ban/filter.d/haproxy-status.conf <<'F2B_FILTER'
[Definition]
failregex = ^.*<HOST>:[0-9]+ .* (401|403|404|429) .*$
ignoreregex =
F2B_FILTER

cat > /etc/fail2ban/jail.d/haproxy.local <<'F2B_JAIL'
[haproxy-status]
enabled  = true
filter   = haproxy-status
logpath  = /var/log/haproxy.log
maxretry = 50
findtime = 5m
bantime  = 1h
F2B_JAIL

systemctl enable --now fail2ban

echo "==> Configuring unattended security upgrades"
dpkg-reconfigure -f noninteractive unattended-upgrades

echo "==> Enabling HAProxy and keepalived"
systemctl enable --now haproxy
systemctl restart haproxy
systemctl enable --now keepalived
systemctl restart keepalived

echo "==> Waiting for HAProxy listeners on :80 and :443"
for i in {1..30}; do
  if ss -lntp | grep -q ':443' && ss -lntp | grep -q ':80'; then
    break
  fi
  sleep 1
done

if ! ss -lntp | grep -q ':443'; then
  echo "HAProxy did not bind :443"
  systemctl status haproxy --no-pager -l || true
  journalctl -u haproxy -n 120 --no-pager || true
  exit 1
fi

echo
echo "========================================"
echo "DONE (${NODE_ROLE})"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443)\b' || true
echo
echo "Stats socket (Unix):"
echo "show info" | socat - UNIX-CONNECT:/run/haproxy/admin.sock | head -10 || true
echo
echo "Services:"
systemctl is-active haproxy keepalived fail2ban chrony ufw || true
echo
echo "VIP state on this node:"
ip -4 addr show "${NODE_IFACE}" | grep "${VIP_ADDR_ONLY}" || echo "VIP not on this node (BACKUP is correct on backup node)"
echo
echo "Keepalived state:"
journalctl -u keepalived -n 20 --no-pager || true
echo
echo "Next steps:"
echo "  1) Place per-site PEM files into /etc/haproxy/certs/ (combined cert+key, mode 600)"
echo "  2) systemctl reload haproxy"
echo "  3) Failover test: stop haproxy on master, watch journalctl -u keepalived on backup"

Rendez-le exécutable et lancez-le sur chaque nœud (avec les variables d’environnement propres au nœud) :

chmod 700 /root/setup-haproxy-keepalived-ubuntu22.sh

# Sur nœud-a (maître) :
export NODE_ROLE=master NODE_IFACE=eth0 NODE_IP=10.0.0.10 PEER_IP=10.0.0.11 \
       VIP_CIDR=10.0.0.50/24 VRRP_AUTH_PASS=Sh4r3dV1p
/root/setup-haproxy-keepalived-ubuntu22.sh

# Sur nœud-b (réplica de secours) :
export NODE_ROLE=backup NODE_IFACE=eth0 NODE_IP=10.0.0.11 PEER_IP=10.0.0.10 \
       VIP_CIDR=10.0.0.50/24 VRRP_AUTH_PASS=Sh4r3dV1p
/root/setup-haproxy-keepalived-ubuntu22.sh

Une fois les deux nœuds en place, faites un vrai test de bascule : systemctl stop haproxy sur le maître, regardez journalctl -u keepalived -f sur le secondaire, confirmez que la VIP migre en quelques secondes, puis redémarrez HAProxy et confirmez la préemption. Déposez les fichiers PEM des sites dans /etc/haproxy/certs/ (chaque fichier contient la chaîne complète plus la clé privée, mode 600), puis systemctl reload haproxy. Le script ne configure pas de sauvegardes au niveau hôte — l’hypothèse est que la VM a des instantanés/sauvegardes au niveau cloud.

Quand la paire HA gouverne une charge réglementée et que vous avez besoin d’une couverture de garde avec runbooks de bascule documentés, c’est exactement ce que livre Environnements infogérés (Environnements infogérés) — réservez une revue.