REPMGR – Gestion automatisée de la réplication et failover
Bonne lecture et bon apprentissage !
Junior TSAFACK – 20/08/2026
⏱️ Temps de lecture estimé : 12 minutes
Dans le cours précédent, vous avez appris à configurer manuellement une réplication physique entre un master et un slave. Mais en production, la gestion manuelle du failover n’est pas acceptable : il faut automatiser la détection de panne et la bascule. C’est là qu’intervient REPMGR (Replication Manager).
REPMGR est une suite d’outils open source qui simplifie l’administration de la réplication PostgreSQL et automatise le failover. Développé par EDB (EnterpriseDB), il est compatible avec PostgreSQL 10 à 16. Ce cours vous présente son installation, sa configuration et son fonctionnement.
Qu’est-ce que REPMGR ?
Section titled “Qu’est-ce que REPMGR ?”REPMGR est un gestionnaire de réplication qui transforme un ensemble de serveurs PostgreSQL en un cluster cohérent. Il se compose de deux éléments principaux :
| Composant | Rôle |
|---|---|
| repmgr (CLI) | Outil en ligne de commande pour administrer le cluster (enregistrement, clone, promotion, suivi). |
| repmgrd (Daemon) | Service qui tourne en arrière-plan sur chaque nœud, surveille la santé du cluster et déclenche le failover automatique. |
Fonctionnalités clés
Section titled “Fonctionnalités clés”- Clone automatique : initialisation d’un standby à partir du master (
repmgr standby clone). - Enregistrement des nœuds : chaque nœud est référencé dans une base de données de métadonnées.
- Promotion manuelle ou automatique : passage d’un standby en master.
- Reconfiguration automatique : les autres standbys se reconnectent au nouveau master (
repmgr standby follow). - Surveillance : affichage de l’état du cluster (
repmgr cluster show). - Témoin (Witness) : nœud sans données qui assure le quorum en cas de split-brain.
Architecture d’un cluster REPMGR
Section titled “Architecture d’un cluster REPMGR”┌──────────────────────────────────────────────────────────────────────┐│ CLUSTER REPMGR ││ ││ ┌──────────────────────────────────────────────────────────────┐ ││ │ NŒUD MASTER (Primary) │ ││ │ ┌─────────────────────────────────────────────────────────┐ │ ││ │ │ PostgreSQL (lecture/écriture) + repmgrd │ │ ││ │ └─────────────────────────────────────────────────────────┘ │ ││ └──────────────────────────────────────────────────────────────┘ ││ │ ││ │ Streaming Replication ││ ▼ ││ ┌──────────────────────────────────────────────────────────────┐ ││ │ NŒUD STANDBY (Slave) │ ││ │ ┌─────────────────────────────────────────────────────────┐ │ ││ │ │ PostgreSQL (lecture seule) + repmgrd │ │ ││ │ └─────────────────────────────────────────────────────────┘ │ ││ └──────────────────────────────────────────────────────────────┘ ││ │ ││ │ (Optionnel) ││ ▼ ││ ┌──────────────────────────────────────────────────────────────┐ ││ │ NŒUD WITNESS (Témoin) │ ││ │ ┌─────────────────────────────────────────────────────────┐ │ ││ │ │ PostgreSQL (sans données) + repmgrd │ │ ││ │ └─────────────────────────────────────────────────────────┘ │ ││ └──────────────────────────────────────────────────────────────┘ ││ ││ ┌──────────────────────────────────────────────────────────────┐ ││ │ BASE DE DONNÉES DE MÉTADONNÉES │ ││ │ ┌─────────────────────────────────────────────────────────┐ │ ││ │ │ Base "repmgr" – contient l'état de chaque nœud │ │ ││ │ └─────────────────────────────────────────────────────────┘ │ ││ └──────────────────────────────────────────────────────────────┘ │└──────────────────────────────────────────────────────────────────────┘Installation de REPMGR
Section titled “Installation de REPMGR”Prérequis
Section titled “Prérequis”Avant d’installer REPMGR, assurez-vous que :
- PostgreSQL est installé et configuré sur chaque nœud.
- Les connexions réseau entre les nœuds sont possibles (port 5432).
- L’authentification SSH sans mot de passe est configurée entre les nœuds (pour
rsync).
1. Installation sur Debian / Ubuntu
Section titled “1. Installation sur Debian / Ubuntu”# Ajouter le dépôt PostgreSQL officiel (si ce n'est pas déjà fait)sudo apt install curl ca-certificatescurl https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'sudo apt update
# Installer REPMGR pour PostgreSQL 16sudo apt install postgresql-16-repmgr2. Installation sur CentOS / RHEL / Rocky Linux
Section titled “2. Installation sur CentOS / RHEL / Rocky Linux”# Installer le dépôt PostgreSQLsudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm
# Installer REPMGRsudo dnf install -y postgresql16-server postgresql16-repmgr3. Vérification de l’installation
Section titled “3. Vérification de l’installation”repmgr --version# Exemple : repmgr 5.5.0
repmgrd --version# Exemple : repmgrd 5.5.0Configuration du cluster REPMGR
Section titled “Configuration du cluster REPMGR”Environnement de test
Section titled “Environnement de test”| Nœud | Rôle | Adresse IP | Hostname |
|---|---|---|---|
| node1 | Primary (Master) | 192.168.60.3 | pg-primary |
| node2 | Standby (Slave) | 192.168.60.4 | pg-standby |
| node3 | Witness (Témoin) | 192.168.60.5 | pg-witness |
Étape 1 : Préparation de PostgreSQL sur chaque nœud
Section titled “Étape 1 : Préparation de PostgreSQL sur chaque nœud”1.1 Configurer postgresql.conf
Section titled “1.1 Configurer postgresql.conf”listen_addresses = '*'wal_level = replicamax_wal_senders = 15max_replication_slots = 15hot_standby = onwal_keep_segments = 100
# Charger la bibliothèque REPMGR (nécessite un redémarrage)shared_preload_libraries = 'repmgr'⚠️ Important : Le paramètre
shared_preload_libraries = 'repmgr'nécessite un redémarrage complet de PostgreSQL pour être pris en compte.
1.2 Configurer pg_hba.conf
Section titled “1.2 Configurer pg_hba.conf”# Connexion locale pour l'utilisateur postgreslocal all postgres peer
# Connexion pour l'utilisateur repmgr (base repmgr)host repmgr repmgr 192.168.60.0/24 scram-sha-256
# Connexion pour la réplicationhost replication repmgr 192.168.60.0/24 scram-sha-256
# Connexions pour les autres utilisateurs (ex : application)host all all 0.0.0.0/0 scram-sha-256💡 Bon à savoir :
scram-sha-256est la méthode de hachage recommandée depuis PostgreSQL 14. Utilisezmd5si vous êtes sur une version plus ancienne.
Étape 2 : Création de l’utilisateur et de la base repmgr
Section titled “Étape 2 : Création de l’utilisateur et de la base repmgr”Sur le nœud primary uniquement :
# Se connecter en tant que postgressudo -u postgres psql-- Créer l'utilisateur repmgrCREATE USER repmgr WITH SUPERUSER CREATEDB CREATEROLE REPLICATION LOGIN ENCRYPTED PASSWORD 'repmgr_password';
-- Créer la base de données repmgr (métadonnées)CREATE DATABASE repmgr OWNER repmgr;
-- Quitter\q💡 Bon à savoir : L’utilisateur
repmgra besoin des droitsSUPERUSER,CREATEDB,CREATEROLEetREPLICATIONpour gérer le cluster.
Étape 3 : Configuration de REPMGR sur chaque nœud
Section titled “Étape 3 : Configuration de REPMGR sur chaque nœud”3.1 Créer le fichier repmgr.conf
Section titled “3.1 Créer le fichier repmgr.conf”Sur chaque nœud, créez le fichier /etc/postgresql/16/main/repmgr.conf (ou /etc/repmgr.conf) :
Sur node1 (primary) :
node_id=1node_name='pg-primary'conninfo='host=192.168.60.3 port=5432 user=repmgr dbname=repmgr connect_timeout=2'data_directory='/var/lib/postgresql/16/main'use_replication_slots=yesmonitoring_history=yes
# Paramètres de connexion pour repmgrdreconnect_attempts=3reconnect_interval=10
# Commandes de service PostgreSQL (pour Debian/Ubuntu)service_start_command = '/usr/bin/pg_ctlcluster 16 main start'service_stop_command = '/usr/bin/pg_ctlcluster 16 main stop'service_restart_command = '/usr/bin/pg_ctlcluster 16 main restart'service_reload_command = '/usr/bin/pg_ctlcluster 16 main reload'service_promote_command = '/usr/bin/pg_ctlcluster 16 main promote'
# Configuration du failover automatiquefailover=automaticpromote_command='/usr/bin/repmgr standby promote -f /etc/postgresql/16/main/repmgr.conf --log-to-file'follow_command='/usr/bin/repmgr standby follow -f /etc/postgresql/16/main/repmgr.conf --log-to-file --upstream-node-id=%n'
# Logslog_file='/var/log/postgresql/repmgr.log'log_level=INFOSur node2 (standby) :
node_id=2node_name='pg-standby'conninfo='host=192.168.60.4 port=5432 user=repmgr dbname=repmgr connect_timeout=2'data_directory='/var/lib/postgresql/16/main'use_replication_slots=yesmonitoring_history=yes
reconnect_attempts=3reconnect_interval=10
service_start_command = '/usr/bin/pg_ctlcluster 16 main start'service_stop_command = '/usr/bin/pg_ctlcluster 16 main stop'service_restart_command = '/usr/bin/pg_ctlcluster 16 main restart'service_reload_command = '/usr/bin/pg_ctlcluster 16 main reload'service_promote_command = '/usr/bin/pg_ctlcluster 16 main promote'
failover=automaticpromote_command='/usr/bin/repmgr standby promote -f /etc/postgresql/16/main/repmgr.conf --log-to-file'follow_command='/usr/bin/repmgr standby follow -f /etc/postgresql/16/main/repmgr.conf --log-to-file --upstream-node-id=%n'
log_file='/var/log/postgresql/repmgr.log'log_level=INFOSur node3 (witness) :
node_id=3node_name='pg-witness'conninfo='host=192.168.60.5 port=5432 user=repmgr dbname=repmgr connect_timeout=2'data_directory='/var/lib/postgresql/16/main'use_replication_slots=yesmonitoring_history=yes
reconnect_attempts=3reconnect_interval=10
service_start_command = '/usr/bin/pg_ctlcluster 16 main start'service_stop_command = '/usr/bin/pg_ctlcluster 16 main stop'service_restart_command = '/usr/bin/pg_ctlcluster 16 main restart'service_reload_command = '/usr/bin/pg_ctlcluster 16 main reload'service_promote_command = '/usr/bin/pg_ctlcluster 16 main promote'
failover=automaticpromote_command='/usr/bin/repmgr standby promote -f /etc/postgresql/16/main/repmgr.conf --log-to-file'follow_command='/usr/bin/repmgr standby follow -f /etc/postgresql/16/main/repmgr.conf --log-to-file --upstream-node-id=%n'
log_file='/var/log/postgresql/repmgr.log'log_level=INFO💡 Bon à savoir : Les paramètres
promote_commandetfollow_commandsont obligatoires pour le failover automatique. Le%ndansfollow_commandest remplacé par l’ID du nouveau primary.
Étape 4 : Enregistrement du cluster
Section titled “Étape 4 : Enregistrement du cluster”4.1 Sur le primary (node1)
Section titled “4.1 Sur le primary (node1)”# Redémarrer PostgreSQL pour charger shared_preload_librariessudo systemctl restart postgresql
# Enregistrer le primarysudo -u postgres repmgr -f /etc/postgresql/16/main/repmgr.conf primary registerRésultat attendu :
INFO: connecting to primary database...NOTICE: attempting to install extension "repmgr"NOTICE: "repmgr" extension installed successfullyNOTICE: primary node record (ID: 1) registered4.2 Sur le standby (node2)
Section titled “4.2 Sur le standby (node2)”# Arrêter PostgreSQLsudo systemctl stop postgresql
# Supprimer les données existantessudo rm -rf /var/lib/postgresql/16/main/*
# Cloner depuis le primarysudo -u postgres repmgr -h 192.168.60.3 -U repmgr -d repmgr -f /etc/postgresql/16/main/repmgr.conf standby clone
# Démarrer PostgreSQLsudo systemctl start postgresql
# Enregistrer le standbysudo -u postgres repmgr -f /etc/postgresql/16/main/repmgr.conf standby register4.3 Sur le witness (node3)
Section titled “4.3 Sur le witness (node3)”# Arrêter PostgreSQLsudo systemctl stop postgresql
# Supprimer les données existantessudo rm -rf /var/lib/postgresql/16/main/*
# Cloner depuis le primary (option --dry-run pour vérifier)sudo -u postgres repmgr -h 192.168.60.3 -U repmgr -d repmgr -f /etc/postgresql/16/main/repmgr.conf standby clone --dry-run
# Cloner réellementsudo -u postgres repmgr -h 192.168.60.3 -U repmgr -d repmgr -f /etc/postgresql/16/main/repmgr.conf standby clone
# Démarrer PostgreSQLsudo systemctl start postgresql
# Enregistrer le witnesssudo -u postgres repmgr -f /etc/postgresql/16/main/repmgr.conf witness registerGestion du cluster avec REPMGR
Section titled “Gestion du cluster avec REPMGR”Voir l’état du cluster
Section titled “Voir l’état du cluster”sudo -u postgres repmgr -f /etc/postgresql/16/main/repmgr.conf cluster showRésultat attendu :
ID | Name | Role | Status | Upstream | Location | Priority | Timeline | Connection string----+--------------+---------+-----------+----------+----------+----------+----------+----------------------------------- 1 | pg-primary | primary | running | | default | 100 | 1 | host=192.168.60.3 port=5432 ... 2 | pg-standby | standby | running | pg-primary | default | 100 | 1 | host=192.168.60.4 port=5432 ... 3 | pg-witness | witness | running | pg-primary | default | 0 | n/a | host=192.168.60.5 port=5432 ...Autres commandes utiles
Section titled “Autres commandes utiles”| Commande | Description |
|---|---|
repmgr node status |
Affiche l’état du nœud local. |
repmgr cluster matrix |
Affiche la matrice de connectivité entre les nœuds. |
repmgr cluster crosscheck |
Vérifie les connexions entre tous les nœuds. |
repmgr standby switchover |
Bascule planifiée (sans perte de données). |
Failover automatique avec repmgrd
Section titled “Failover automatique avec repmgrd”Démarrer repmgrd sur chaque nœud
Section titled “Démarrer repmgrd sur chaque nœud”# Sur chaque nœud, démarrer le daemonsudo systemctl start repmgrdsudo systemctl enable repmgrdConfiguration du failover automatique
Section titled “Configuration du failover automatique”Les paramètres suivants dans repmgr.conf activent le failover automatique :
failover=automaticpromote_command='/usr/bin/repmgr standby promote -f /etc/postgresql/16/main/repmgr.conf --log-to-file'follow_command='/usr/bin/repmgr standby follow -f /etc/postgresql/16/main/repmgr.conf --log-to-file --upstream-node-id=%n'Paramètres de surveillance
Section titled “Paramètres de surveillance”| Paramètre | Défaut | Description |
|---|---|---|
monitor_interval_secs |
2 | Intervalle (en secondes) entre les vérifications de l’upstream. |
connection_check_type |
ping |
Méthode de vérification (ping, connection, query). |
reconnect_attempts |
6 | Nombre de tentatives avant de déclencher un failover. |
reconnect_interval |
10 | Intervalle (en secondes) entre les tentatives. |
Scénario de failover
Section titled “Scénario de failover”- Détection : repmgrd sur le standby détecte que le primary est inaccessible (après
reconnect_attemptséchecs). - Promotion : repmgrd exécute
promote_commandsur le standby qui devient le nouveau primary. - Reconfiguration : repmgrd exécute
follow_commandsur les autres standbys pour qu’ils suivent le nouveau primary. - Mise à jour des métadonnées : repmgr met à jour la base
repmgr.
Logs de failover
Section titled “Logs de failover”# Voir les logs de repmgrdsudo tail -f /var/log/postgresql/repmgr.logExemple de logs :
2024-01-15 14:30:25.123 LOG: monitoring primary node "pg-primary" (ID: 1)2024-01-15 14:30:35.456 WARNING: connection to upstream node "pg-primary" lost2024-01-15 14:30:45.789 WARNING: reconnection attempts exhausted2024-01-15 14:30:45.790 INFO: promoting standby "pg-standby" to primary2024-01-15 14:30:50.123 INFO: promotion successful2024-01-15 14:30:50.124 INFO: standbys following new primary "pg-standby"Bascule planifiée (Switchover)
Section titled “Bascule planifiée (Switchover)”Contrairement au failover (panne), le switchover est une bascule planifiée sans perte de données.
# Sur le primary actuelsudo -u postgres repmgr -f /etc/postgresql/16/main/repmgr.conf standby switchover --siblings-followDéroulement :
- REPMGR vérifie que tous les standbys sont à jour.
- Le primary se dégrade en standby.
- Un standby est promu en primary.
- Les autres standbys se reconnectent au nouveau primary.
Resynchronisation après un failover
Section titled “Resynchronisation après un failover”Lorsque l’ancien primary revient en ligne, il doit être resynchronisé et réintégré comme standby.
Méthode manuelle
Section titled “Méthode manuelle”# Sur l'ancien primary (devenu hors cluster)sudo systemctl stop postgresqlsudo rm -rf /var/lib/postgresql/16/main/*
# Cloner depuis le nouveau primarysudo -u postgres repmgr -h 192.168.60.4 -U repmgr -d repmgr -f /etc/postgresql/16/main/repmgr.conf standby clone
# Démarrer PostgreSQLsudo systemctl start postgresql
# Réenregistrer comme standbysudo -u postgres repmgr -f /etc/postgresql/16/main/repmgr.conf standby register --forceNettoyage de l’ancien primary dans les métadonnées
Section titled “Nettoyage de l’ancien primary dans les métadonnées”# Sur le nouveau primarysudo -u postgres repmgr -f /etc/postgresql/16/main/repmgr.conf primary unregister --node-id=1Témoin (Witness) – Pourquoi et comment ?
Section titled “Témoin (Witness) – Pourquoi et comment ?”Un witness est un nœud sans données qui ne fait que participer au quorum. Il est utile dans un cluster à 2 nœuds pour éviter le split-brain (situation où chaque nœud pense être le primary).
Enregistrement d’un witness
Section titled “Enregistrement d’un witness”sudo -u postgres repmgr -f /etc/postgresql/16/main/repmgr.conf witness registerVérification
Section titled “Vérification”sudo -u postgres repmgr -f /etc/postgresql/16/main/repmgr.conf cluster show# Le witness apparaît avec le rôle "witness"REPMGR vs Patroni
Section titled “REPMGR vs Patroni”| Critère | REPMGR | Patroni |
|---|---|---|
| Complexité | Simple | Complexe (nécessite un DCS comme etcd) |
| Dépendances | PostgreSQL uniquement | PostgreSQL + DCS (etcd, ZooKeeper, Consul) |
| Failover | Automatique avec repmgrd | Automatique via DCS |
| Gestion des configurations | Fichiers statiques | Stockée dans le DCS |
| Cas d’usage | Petits clusters, équipes réduites | Grands clusters, infrastructures modernes |
💡 Bon à savoir : REPMGR est plus simple à mettre en œuvre et à maintenir pour des clusters de 2 à 5 nœuds. Patroni est plus adapté aux grandes infrastructures avec des exigences complexes.
Bonnes pratiques
Section titled “Bonnes pratiques”| Pratique | Description |
|---|---|
| Utiliser un witness | Pour les clusters à 2 nœuds, un witness évite le split-brain. |
| Configurer les commandes de service | Utilisez service_restart_command adapté à votre OS (systemd). |
| Surveiller les logs | Activez log_file et log_level=INFO pour diagnostiquer les problèmes. |
| Tester le failover | Simulez régulièrement une panne pour vérifier la procédure. |
| Utiliser des replication slots | Activez use_replication_slots=yes pour éviter la suppression prématurée des WAL. |
| Sécuriser les connexions | Utilisez scram-sha-256 pour l’authentification. |
| Documenter la procédure | Documentez les commandes de switchover et de resynchronisation. |
Commandes récapitulatives
Section titled “Commandes récapitulatives”| Action | Commande |
|---|---|
| Enregistrer le primary | repmgr primary register |
| Enregistrer un standby | repmgr standby register |
| Enregistrer un witness | repmgr witness register |
| Cloner un standby | repmgr standby clone -h <master> -U repmgr |
| Promouvoir un standby | repmgr standby promote |
| Bascule planifiée | repmgr standby switchover --siblings-follow |
| Voir l’état du cluster | repmgr cluster show |
| Démarrer repmgrd | sudo systemctl start repmgrd |
| Voir les logs | tail -f /var/log/postgresql/repmgr.log |
Prochain chapitre
Section titled “Prochain chapitre”Vous savez maintenant configurer un cluster REPMGR avec failover automatique. Dans le prochain et dernier cours, nous aborderons le PITR (Point-In-Time Recovery) avec les WAL, pour une restauration à un instant précis.
👉 Cours 14 : PITR et archivage des WAL
Junior TSAFACK – 20/08/2026