← Start of tutorial

WIUNIX ACADEMY

PostgreSQL with Patroni: replication, quorum and safe switchover

Page 3 of 6. Review the earlier steps and prerequisites before continuing.

YOUR SYSTEM. YOUR STEPS.

Where are you working?

Choose your OS and version. The prerequisites, commands and troubleshooting follow your environment.

Rocky Linux 10.2Reviewed against official documentation ·

USE YOUR OWN VALUES

Configure this tutorial

Set the example values for your environment; related explanations and copy panels update together. Never enter passwords, private keys or tokens. Values stay in this tab and are not sent to the server or share links. Check actual DNS, certificates and network policy before running commands.

Different IP addresses, domains or ports? Open the settings below, change the values and select “Apply to tutorial”, then copy the updated commands.

Set values for my environment11 editable values
07

LET’S BUILD

Generate the node and edit secrets privately

This panel is for pg1 ONLY. On pg2 replace the final argument1 with2; on pg3 use3. Do not change the cluster IP list. In the protected editor replace all four REPLACE sentinels with independently generated strong passwords, identical for the corresponding role on all three nodes. The superuser is deliberately privileged for this lab, including rewind; production needs a reviewed least-privilege rewind design. Patroni creates the REPLICATION LOGIN role at bootstrap. It must not be an application superuser. Config contains secrets: never print it, commit it or send it as a support attachment.

Bash

Disposable database VM; Bash as administrator

set -eu
sudo -u postgres python3 '/srv/academy-pg18/make-config.py' 1
sudo -u postgres nano '/srv/academy-pg18/patroni.yml'
sudo -u postgres /usr/bin/patroni --validate-config '/srv/academy-pg18/patroni.yml'
How do I know it worked?

Only new configs created, all sentinels privately replaced, validation succeeds; no database starts.

08

LET’S BUILD

Save a dedicated etcd unit

On every VM save the next unit. It is a lab-owned service with a dedicated data path; the distribution etcd service is not used. Starting this fresh cluster initializes the selected DCS data directories. Do not use initial-cluster-state new against a recovered or existing DCS.

Bash

Disposable database VM; Bash as administrator

sudo nano /etc/systemd/system/academy-pg-etcd.service
How do I know it worked?

Save the complete unit below.

09

LET’S BUILD

File: etcd service

Stop/restart affects this voter only. With three healthy voters, one restart retains a majority; two concurrent outages lose quorum.

INI · /etc/systemd/system/academy-pg-etcd.service

Disposable database VM; Bash as administrator

[Unit]
Description=Academy isolated PostgreSQL lab DCS
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=postgres
Group=postgres
UMask=0077
ExecStart=/opt/academy-etcd-3.7.3/etcd --config-file=/srv/academy-pg18/etcd.yml
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
How do I know it worked?

Unit points to the reviewed binary and dedicated config.

10

LET’S BUILD

Check host policy before starting any voter

On each fresh node keep SELinux enforcing. Label only this lab root for PostgreSQL data and its socket separately; the etcd executable gets the ordinary binary label, not a dedicated confined etcd domain. Patroni/DCS under the shared postgres Unix identity is lab simplification, not a production least-privilege policy. After startup inspect actual process labels and AVCs. A PostgreSQL listener port assigned to another SELinux service stops the path rather than relabeling that service.

firewalld must already be active with preserved SSH and default-deny exposure. internal is a sample zone: substitute the actual private-interface zone from get-active-zones before running. Inspect broad services/rules/zone target and upstream ACLs first. Rules allow the three peers and exact admin source to PostgreSQL/API/DCS and only peers to the peer port, in runtime/permanent state without reload. Record pre-existing versus added rules; retire only the exact lab additions. Do not flush or switch the firewall.

Bash

Each fresh lab VM · policy review before startup

(
set -euo pipefail
getenforce
sudo python3 - <<'PY'
import re,subprocess
root='/srv/academy-pg18'
for pattern,kind in [(re.escape(root)+'(/.*)?','postgresql_db_t'),(re.escape(root+'/socket')+'(/.*)?','postgresql_var_run_t')]:
    subprocess.run(['semanage','fcontext','-a','-t',kind,pattern],check=True)
subprocess.run(['semanage','fcontext','-a','-t','bin_t',re.escape('/opt/academy-etcd-3.7.3/etcd')],check=True)
rows=subprocess.check_output(['semanage','port','-l'],text=True).splitlines()
port=5432
owners=set()
for row in rows:
    fields=row.split(None,2)
    if len(fields)!=3 or fields[1]!='tcp':continue
    for token in fields[2].replace(',',' ').split():
        bounds=token.split('-');low=int(bounds[0]);high=int(bounds[-1])
        if low<=port<=high and fields[0] not in ('unreserved_port_t','reserved_port_t','port_t'):owners.add(fields[0])
if owners and owners!={'postgresql_port_t'}:raise SystemExit('Port belongs to another SELinux service; STOP')
if not owners:subprocess.run(['semanage','port','-a','-t','postgresql_port_t','-p','tcp',str(port)],check=True)
subprocess.run(['restorecon','-Rv',root,'/opt/academy-etcd-3.7.3/etcd'],check=True)
PY
sudo firewall-cmd --state
sudo firewall-cmd --get-active-zones
zone=internal
sudo firewall-cmd --zone="$zone" --list-all
for source in 10.77.18.11 10.77.18.12 10.77.18.13 10.77.18.50; do
  for port in 5432 8008 2379; do
    rule=$(printf 'rule family="ipv4" source address="%s/32" port port="%s" protocol="tcp" accept' "$source" "$port")
    sudo firewall-cmd --zone="$zone" --add-rich-rule="$rule"
    sudo firewall-cmd --permanent --zone="$zone" --add-rich-rule="$rule"
  done
done
for source in 10.77.18.11 10.77.18.12 10.77.18.13; do
  rule=$(printf 'rule family="ipv4" source address="%s/32" port port="2380" protocol="tcp" accept' "$source")
  sudo firewall-cmd --zone="$zone" --add-rich-rule="$rule"
  sudo firewall-cmd --permanent --zone="$zone" --add-rich-rule="$rule"
done
sudo firewall-cmd --zone="$zone" --list-rich-rules
)
How do I know it worked?

Private routing, intended source rules and active host policy are known; unresolved denials stop startup.

11

LET’S BUILD

Start only the three DCS voters

Run on all three VMs, then use the admin panel below. No Patroni node starts until endpoint health, membership, TLS and scoped access pass. Service logs can include private addresses; inspect locally.

Bash

Disposable database VM; Bash as administrator

sudo systemctl daemon-reload
sudo systemctl start academy-pg-etcd.service
sudo systemctl status academy-pg-etcd.service --no-pager
sudo journalctl -u academy-pg-etcd.service -n 40 --no-pager
How do I know it worked?

Three voters running with TLS; no PostgreSQL process for this lab yet.

12

LET’S BUILD

Give Patroni only its DCS prefix

Run once from the protected root administrator shell on pg1. Provision root.crt, root.key and the trusted CA in the new root-owned directory below /root, outside the service-writable lab tree. Do not give the admin key to postgres. Bootstrap root and the scoped Patroni identity only on an empty DCS; existing users or roles stop this fresh-lab procedure.

Patroni uses the etcd3 gRPC gateway, where certificate-CN authentication is not available like the direct gRPC client. Use a dedicated patroni username/password in its protected config as well as mTLS, and an empty-subject-CN gateway client certificate. Admin and peer certificates retain their identities. Grant only this cluster prefix with its trailing slash; never store authentication passwords in DCS keys. mTLS is already required before enabling RBAC.

Bash

Disposable database VM; Bash as administrator

set -eu
sudo test ! -e '/root/academy-pg-admin-academy_pg18'
sudo test ! -L '/root/academy-pg-admin-academy_pg18'
sudo install -d -o root -g root -m 0700 '/root/academy-pg-admin-academy_pg18'
# Provision root.crt, root.key and the trusted ca.crt here through the protected PKI channel.
sudo python3 - <<'PY'
from pathlib import Path
import os,stat
base=Path('/root/academy-pg-admin-academy_pg18')
if not stat.S_ISDIR(base.lstat().st_mode):raise SystemExit('Unsafe admin directory')
names=('root.crt','root.key','ca.crt')
for name in names:
    if not stat.S_ISREG((base/name).lstat().st_mode):raise SystemExit('Unsafe admin PKI input: '+name)
for name in names:
    path=base/name
    fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW)
    try:
        if not stat.S_ISREG(os.fstat(fd).st_mode):raise SystemExit('Changed admin PKI input: '+name)
        os.chown(path,0,0,follow_symlinks=False)
        os.fchmod(fd,0o600 if name.endswith('.key') else 0o644)
    finally:os.close(fd)
PY
dcs_admin() {
  sudo env ETCDCTL_ENDPOINTS='https://10.77.18.11:2379,https://10.77.18.12:2379,https://10.77.18.13:2379' ETCDCTL_CACERT='/root/academy-pg-admin-academy_pg18/ca.crt' ETCDCTL_CERT='/root/academy-pg-admin-academy_pg18/root.crt' ETCDCTL_KEY='/root/academy-pg-admin-academy_pg18/root.key' /opt/academy-etcd-3.7.3/etcdctl "$@"
}
dcs_admin endpoint health
dcs_admin member list --write-out=table
dcs_admin user list
dcs_admin user add root --no-password
dcs_admin role add root
dcs_admin user grant-role root root
dcs_admin role add academy-pg
dcs_admin role grant-permission academy-pg readwrite '/academy/academy_pg18/' --prefix=true
# Interactive: enter the DCS password also saved in the protected Patroni file.
dcs_admin user add patroni
dcs_admin user grant-role patroni academy-pg
dcs_admin auth enable
dcs_admin endpoint health
How do I know it worked?

Three healthy member IDs, auth enabled, Patroni limited to the new cluster prefix.

Explore all tutorials ↗