Skip to content

Instantly share code, notes, and snippets.

@klaustopher
Created August 29, 2024 08:45
Show Gist options
  • Select an option

  • Save klaustopher/2339b3e463a30bf4773ef41cc0e1b775 to your computer and use it in GitHub Desktop.

Select an option

Save klaustopher/2339b3e463a30bf4773ef41cc0e1b775 to your computer and use it in GitHub Desktop.
Postgres with Replication in a docker compose file
CREATE USER replicator WITH REPLICATION ENCRYPTED PASSWORD 'replicator_password';
SELECT pg_create_physical_replication_slot('replication_slot');
# Source: https://medium.com/@eremeykin/how-to-setup-single-primary-postgresql-replication-with-docker-compose-98c48f233bbf
x-postgres-common: &postgres-common
image: postgres:16-alpine
user: postgres
restart: always
healthcheck:
test: "pg_isready -U user --dbname=postgres"
interval: 10s
timeout: 5s
retries: 5
tmpfs:
- /var/lib/postgresql
services:
postgres_primary:
<<: *postgres-common
ports:
- 5432:5432
environment:
POSTGRES_USER: user
POSTGRES_DB: postgres
POSTGRES_PASSWORD: password
POSTGRES_HOST_AUTH_METHOD: "scram-sha-256\nhost replication all 0.0.0.0/0 md5"
POSTGRES_INITDB_ARGS: "--auth-host=scram-sha-256"
command: |
postgres
-c wal_level=replica
-c hot_standby=on
-c max_wal_senders=10
-c max_replication_slots=10
-c hot_standby_feedback=on
volumes:
- ./00_init.sql:/docker-entrypoint-initdb.d/00_init.sql
postgres_replica:
<<: *postgres-common
ports:
- 5433:5432
environment:
PGUSER: replicator
PGPASSWORD: replicator_password
command: |
bash -c "
until pg_basebackup --pgdata=/var/lib/postgresql/data -R --slot=replication_slot --host=postgres_primary --port=5432
do
echo 'Waiting for primary to connect...'
sleep 1s
done
echo 'Backup done, starting replica...'
chmod 0700 /var/lib/postgresql/data
postgres
"
depends_on:
- postgres_primary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment