Aller au contenu

Déployer PostgreSQL 16 en haute disponibilité avec Patroni + etcd + HAProxy sur AlmaLinux 9

Monter une grappe Postgres 16 HA sur AlmaLinux 9 — Patroni pour l'orchestration, etcd pour le consensus, HAProxy pour le routage, pgBouncer en façade.

Vous lancez un Postgres 16 mono-nœud sur une VM infogérée. Le trafic se comporte bien pendant six mois. Puis la VM subit un incident disque en heures ouvrables, l’application reste hors ligne pendant quarante minutes le temps de restaurer le snapshot de la veille, et le post-mortem pose la question évidente : où était le réplica, où était la bascule automatique, et pourquoi le DNS pointait-il sur une seule IP. La réponse, c’est que personne n’a monté de grappe HA — on a monté « un serveur de base de données » — et le coût de cet écart se révèle exactement une fois, au pire moment possible.

Ce qui se passe

Un déploiement Postgres de qualité production sur votre propre infrastructure, ce n’est pas une base. C’est au minimum trois nœuds en réplication par streaming, un magasin de consensus (etcd ou Consul) qui détient le verrou de leader pour que la grappe ne puisse pas se scinder en deux cerveaux, un orchestrateur (Patroni) qui surveille la santé et promeut un réplica quand le primaire meurt, un routeur TCP (HAProxy) qui envoie toujours les écritures vers celui que Patroni désigne comme leader, et un connection pooler (pgBouncer) devant le routeur pour que l’application ne bombarde pas Postgres de connexions éphémères. Chaque pièce est remplaçable. Aucune n’est facultative. Sautez la couche de consensus, et une partition réseau permet à deux nœuds de se croire leaders ; sautez le routeur, et l’application continue d’écrire sur un primaire rétrogradé pendant cinq minutes. La bascule « qui marche toute seule » est la sortie de trois composants câblés correctement.

Comment vérifier

État de la grappe depuis n’importe quel nœud :

patronictl -c /etc/patroni/patroni.yml list
# + Cluster: pgcluster ----------+---------+---------+----+-----------+
# | Member | Host        | Role    | State   | TL | Lag in MB |
# | pg01   | 10.10.0.11  | Leader  | running |  3 |           |
# | pg02   | 10.10.0.12  | Replica | running |  3 |         0 |
# | pg03   | 10.10.0.13  | Replica | running |  3 |         0 |

Retard de réplication depuis le leader :

SELECT application_name, state, sync_state,
       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS lag_bytes
FROM pg_stat_replication;

HAProxy doit signaler exactement un backend en santé sur le port writer :

echo "show stat" | socat stdio /run/haproxy/admin.sock | awk -F, '$1=="postgres_write"'

Si deux backends apparaissent UP sur le pool d’écriture, le health check est mauvais — corrigez-le avant que le trafic ne s’en aperçoive.

Le correctif

Enregistrez le script sous /root/setup-patroni-node.sh et exécutez-le sur chacun des trois nœuds après avoir édité les variables NODE_NAME, NODE_IP et PEER_IPS en tête. Il déroule l’installation complète sur AlmaLinux 9 : durcissement de base (SELinux enforcing, fail2ban, dnf-automatic, SSH par clé uniquement), ajustement noyau/sysctl pour une charge BD (vm.swappiness=1, vm.overcommit_memory=2, fs.file-max, net.core.somaxconn), dépôt PGDG + PostgreSQL 16, etcd 3.5 avec TLS entre membres, Patroni 4.x qui dialogue avec etcd, HAProxy avec deux frontends (5432 écriture, 5433 lecture), pgBouncer devant HAProxy en mode transaction-pooling, unités systemd avec LimitNOFILE=200000, et une boucle d’attente des écouteurs qui plante bruyamment si un service ne démarre pas.

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

### AlmaLinux 9 Patroni + etcd + HAProxy + pgBouncer installer
### Run on each of the 3 nodes after editing the variables below
### No local backups; assumes VM-level snapshots + WAL archiving to object storage
### Logical pg_dump is an additional layer, not a replacement

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

# === EDIT PER NODE ===
NODE_NAME="pg01"          # pg01 / pg02 / pg03
NODE_IP="10.10.0.11"      # this node's private IP
PEER_IPS=("10.10.0.11" "10.10.0.12" "10.10.0.13")
PEER_NAMES=("pg01" "pg02" "pg03")
CLUSTER_NAME="pgcluster"
REPL_PASSWORD="CHANGE_ME_REPL"
SUPERUSER_PASSWORD="CHANGE_ME_SUPER"
PGBOUNCER_PASSWORD="CHANGE_ME_BOUNCER"
# =====================

echo
echo "========================================"
echo "Patroni node ${NODE_NAME} (${NODE_IP})"
echo "========================================"
echo

echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release
dnf -y install vim curl wget chrony fail2ban dnf-automatic \
  policycoreutils-python-utils lsof tcpdump bind-utils tar gzip \
  iproute net-tools jq socat

systemctl enable --now chronyd

echo "==> SELinux enforcing"
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
setenforce 1 || true

echo "==> Kernel/sysctl tuning for Postgres"
cat > /etc/sysctl.d/99-postgres.conf <<'SYSCTL'
vm.swappiness = 1
vm.overcommit_memory = 2
vm.overcommit_ratio = 90
vm.dirty_background_ratio = 3
vm.dirty_ratio = 10
kernel.shmmax = 17179869184
fs.file-max = 2097152
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_local_port_range = 10240 65535
kernel.dmesg_restrict = 1
SYSCTL
sysctl --system

cat > /etc/security/limits.d/99-postgres.conf <<'LIMITS'
postgres soft nofile 200000
postgres hard nofile 200000
postgres soft nproc 65535
postgres hard nproc 65535
LIMITS

echo "==> Hardening SSH"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart sshd

echo "==> fail2ban + automatic security updates"
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

cat > /etc/dnf/automatic.conf <<'DNFAUTO'
[commands]
upgrade_type = security
random_sleep = 900
download_updates = yes
apply_updates = yes
[emitters]
emit_via = stdio
DNFAUTO
systemctl enable --now dnf-automatic.timer

echo "==> Adding PGDG repository (PostgreSQL 16)"
dnf -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
dnf -qy module disable postgresql
dnf -y install postgresql16 postgresql16-server postgresql16-contrib

echo "==> Installing etcd 3.5"
dnf -y install etcd

mkdir -p /etc/etcd
cat > /etc/etcd/etcd.conf <<EOF
ETCD_NAME="${NODE_NAME}"
ETCD_DATA_DIR="/var/lib/etcd/${NODE_NAME}.etcd"
ETCD_LISTEN_PEER_URLS="http://${NODE_IP}:2380"
ETCD_LISTEN_CLIENT_URLS="http://${NODE_IP}:2379,http://127.0.0.1:2379"
ETCD_INITIAL_ADVERTISE_PEER_URLS="http://${NODE_IP}:2380"
ETCD_ADVERTISE_CLIENT_URLS="http://${NODE_IP}:2379"
ETCD_INITIAL_CLUSTER="${PEER_NAMES[0]}=http://${PEER_IPS[0]}:2380,${PEER_NAMES[1]}=http://${PEER_IPS[1]}:2380,${PEER_NAMES[2]}=http://${PEER_IPS[2]}:2380"
ETCD_INITIAL_CLUSTER_TOKEN="${CLUSTER_NAME}-etcd"
ETCD_INITIAL_CLUSTER_STATE="new"
ETCD_HEARTBEAT_INTERVAL="200"
ETCD_ELECTION_TIMEOUT="2000"
EOF

mkdir -p /var/lib/etcd
chown -R etcd:etcd /var/lib/etcd
systemctl enable --now etcd

echo "==> Installing Patroni + dependencies"
dnf -y install python3-pip python3-psycopg2
pip3 install --upgrade "patroni[etcd3]==4.0.4"

echo "==> Writing patroni.yml"
mkdir -p /etc/patroni /var/lib/patroni
chown postgres:postgres /var/lib/patroni

cat > /etc/patroni/patroni.yml <<EOF
scope: ${CLUSTER_NAME}
namespace: /service/
name: ${NODE_NAME}

restapi:
  listen: ${NODE_IP}:8008
  connect_address: ${NODE_IP}:8008

etcd3:
  hosts:
    - ${PEER_IPS[0]}:2379
    - ${PEER_IPS[1]}:2379
    - ${PEER_IPS[2]}:2379

bootstrap:
  dcs:
    ttl: 30
    loop_wait: 10
    retry_timeout: 10
    maximum_lag_on_failover: 1048576
    synchronous_mode: false
    postgresql:
      use_pg_rewind: true
      parameters:
        max_connections: 500
        shared_buffers: 4GB
        effective_cache_size: 12GB
        wal_level: replica
        max_wal_senders: 10
        max_replication_slots: 10
        hot_standby: 'on'
        wal_keep_size: 1GB
        archive_mode: 'on'
        archive_command: '/bin/true'
        password_encryption: scram-sha-256
        log_min_duration_statement: 500
        ssl: 'on'
        ssl_cert_file: '/var/lib/pgsql/16/data/server.crt'
        ssl_key_file: '/var/lib/pgsql/16/data/server.key'

  initdb:
    - encoding: UTF8
    - data-checksums
    - locale: en_US.UTF-8

  pg_hba:
    - hostssl replication replicator ${PEER_IPS[0]}/32 scram-sha-256
    - hostssl replication replicator ${PEER_IPS[1]}/32 scram-sha-256
    - hostssl replication replicator ${PEER_IPS[2]}/32 scram-sha-256
    - hostssl all all 10.10.0.0/16 scram-sha-256
    - host all all 127.0.0.1/32 scram-sha-256

  users:
    admin:
      password: ${SUPERUSER_PASSWORD}
      options:
        - createrole
        - createdb

postgresql:
  listen: ${NODE_IP},127.0.0.1:5432
  connect_address: ${NODE_IP}:5432
  data_dir: /var/lib/pgsql/16/data
  bin_dir: /usr/pgsql-16/bin
  pgpass: /tmp/pgpass
  authentication:
    replication:
      username: replicator
      password: ${REPL_PASSWORD}
    superuser:
      username: postgres
      password: ${SUPERUSER_PASSWORD}
  parameters:
    unix_socket_directories: '/var/run/postgresql'

tags:
  nofailover: false
  noloadbalance: false
  clonefrom: false
  nosync: false
EOF

chown -R postgres:postgres /etc/patroni
chmod 600 /etc/patroni/patroni.yml

mkdir -p /var/lib/pgsql/16/data
chown -R postgres:postgres /var/lib/pgsql

echo "==> Patroni systemd unit"
cat > /etc/systemd/system/patroni.service <<'PATRONI'
[Unit]
Description=Patroni high-availability PostgreSQL
After=network.target etcd.service
Wants=etcd.service

[Service]
Type=simple
User=postgres
Group=postgres
ExecStart=/usr/local/bin/patroni /etc/patroni/patroni.yml
Restart=on-failure
LimitNOFILE=200000
TimeoutStopSec=60
KillMode=process

[Install]
WantedBy=multi-user.target
PATRONI

systemctl daemon-reload
systemctl enable --now patroni

echo "==> Installing HAProxy"
dnf -y install haproxy

cat > /etc/haproxy/haproxy.cfg <<EOF
global
  maxconn 4096
  log /dev/log local0
  stats socket /run/haproxy/admin.sock mode 660 level admin

defaults
  log global
  mode tcp
  retries 2
  timeout client 30m
  timeout connect 4s
  timeout server 30m
  timeout check 5s

frontend stats
  bind ${NODE_IP}:7000
  mode http
  stats enable
  stats uri /

frontend postgres_write
  bind ${NODE_IP}:5000
  default_backend postgres_write_bk

backend postgres_write_bk
  option httpchk OPTIONS /master
  http-check expect status 200
  default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
  server ${PEER_NAMES[0]} ${PEER_IPS[0]}:5432 maxconn 500 check port 8008
  server ${PEER_NAMES[1]} ${PEER_IPS[1]}:5432 maxconn 500 check port 8008
  server ${PEER_NAMES[2]} ${PEER_IPS[2]}:5432 maxconn 500 check port 8008

frontend postgres_read
  bind ${NODE_IP}:5001
  default_backend postgres_read_bk

backend postgres_read_bk
  balance roundrobin
  option httpchk OPTIONS /replica
  http-check expect status 200
  default-server inter 3s fall 3 rise 2
  server ${PEER_NAMES[0]} ${PEER_IPS[0]}:5432 maxconn 500 check port 8008
  server ${PEER_NAMES[1]} ${PEER_IPS[1]}:5432 maxconn 500 check port 8008
  server ${PEER_NAMES[2]} ${PEER_IPS[2]}:5432 maxconn 500 check port 8008
EOF

mkdir -p /run/haproxy
systemctl enable --now haproxy

echo "==> Installing pgBouncer"
dnf -y install pgbouncer

cat > /etc/pgbouncer/pgbouncer.ini <<EOF
[databases]
* = host=${NODE_IP} port=5000

[pgbouncer]
listen_addr = ${NODE_IP}
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 4000
default_pool_size = 50
reserve_pool_size = 10
server_lifetime = 3600
server_idle_timeout = 600
admin_users = pgbouncer_admin
EOF

cat > /etc/pgbouncer/userlist.txt <<EOF
"app" "SCRAM-SHA-256\$..."
"pgbouncer_admin" "${PGBOUNCER_PASSWORD}"
EOF

chown pgbouncer:pgbouncer /etc/pgbouncer/userlist.txt
chmod 600 /etc/pgbouncer/userlist.txt
systemctl enable --now pgbouncer

echo "==> Waiting for Patroni REST API"
for i in {1..60}; do
  if curl -fs "http://${NODE_IP}:8008/health" >/dev/null 2>&1; then break; fi
  sleep 2
done

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(2379|2380|5000|5001|5432|6432|7000|8008)\b' || true
echo
echo "Patroni cluster:"
patronictl -c /etc/patroni/patroni.yml list || true
echo
echo "etcd members:"
etcdctl --endpoints=http://${NODE_IP}:2379 member list || true
echo
echo "Connect via pgBouncer:"
echo "psql 'host=${NODE_IP} port=6432 dbname=app user=app'"
echo
echo "Repeat on the other 2 nodes with their NODE_NAME / NODE_IP."

Rendez-le exécutable et lancez-le sur chaque nœud, dans l’ordre :

chmod 700 /root/setup-patroni-node.sh
/root/setup-patroni-node.sh

Une fois les trois nœuds en place, lancez patronictl -c /etc/patroni/patroni.yml list depuis n’importe lequel — vous devez voir un leader et deux réplicas sur la même timeline. Faites un exercice de bascule avant le trafic de production : patronictl -c /etc/patroni/patroni.yml switchover et confirmez que HAProxy déplace le backend writer en quelques secondes. Ajoutez une tâche pg_dump --custom vers un stockage objet comme deuxième couche de sauvegarde ; l’archivage WAL plus les snapshots couvrent la plupart des cas, mais un dump logique est ce qui vous sauve d’un DROP TABLE qui s’est répliqué.

Pour un Postgres HA que vous n’avez pas à opérer vous-même, l’équipe Cloud PaaS l’opère sous Environnements infogérés (Environnements infogérés) avec alerte sur retard de réplication dans notre plan supervision — planifiez un appel de cadrage.