Skip to content

Instantly share code, notes, and snippets.

@joshmoore
Last active August 29, 2015 14:22
Show Gist options
  • Save joshmoore/0efca2d298dd7abf1dce to your computer and use it in GitHub Desktop.
Save joshmoore/0efca2d298dd7abf1dce to your computer and use it in GitHub Desktop.
docker/postgres replication
#!/bin/bash
# https://groups.google.com/forum/#!topic/docker-user/ysAx3_oP8zI
set -e
set -u
set -x
PGMASTER=testmaster
PGSLAVE=testslave
PGNAME=testdb
PGUSER=testuser
PGPASS=testpass
PGREPL=testrepl
PGDIR1=/tmp/postgres1
PGDIR2=/tmp/postgres2
docker stop $PGMASTER $PGSLAVE || echo not running \?
docker rm $PGMASTER $PGSLAVE || echo doesn\'t exist \?
rm -rf /tmp/postgres1
rm -rf /tmp/postgres2
docker run --name $PGMASTER -e POSTGRES_USER=$PGUSER -e POSTGRES_PASSWORD=$PGPASS -v $PGDIR1:/var/lib/postgresql/data -d postgres
sleep 5
docker run -it --rm --link $PGMASTER:db -e PGPASSWORD=$PGPASS postgres sh -c "createdb -h db $PGNAME -U$PGUSER"
docker run -it --rm --link $PGMASTER:db -e PGPASSWORD=$PGPASS postgres sh -c "psql -h db $PGNAME -U$PGUSER"
# Allow all hosts to replicate with this 'master' DB
echo 'host replication replicator 0.0.0.0/0 trust' >> $PGDIR1/pg_hba.conf
cat << EOF >> $PGDIR1/postgresql.conf
wal_level = hot_standby
checkpoint_segments = 8
max_wal_senders = 3
wal_keep_segments = 8
hot_standby = on
EOF
# Restart container
docker stop $PGMASTER
chmod 700 $PGDIR1
docker start $PGMASTER
sleep 5
docker run -it --rm --link $PGMASTER:db -e POSTGRES_USER=$PGUSER -e PGPASSWORD=$PGPASS \
postgres sh -c "psql -h db $PGNAME -U$PGUSER -c \"CREATE USER replicator REPLICATION LOGIN ENCRYPTED PASSWORD '$PGREPL';\""
docker run -it --rm --link $PGMASTER:db -e POSTGRES_USER=$PGUSER -e POSTGRES_PASSWORD=$PGPASS \
-v $PGDIR2:/var/lib/postgresql/data \
postgres sh -c 'pg_basebackup -h db -D /var/lib/postgresql/data -U replicator -P -v -x'
chmod 700 $PGDIR2
cat << EOF > $PGDIR2/recovery.conf
primary_conninfo = 'host=db port=5432 user=replicator password=thepassword'
trigger_file = '/var/lib/postgresql/data/failover'
standby_mode = 'on'
EOF
docker run --name $PGSLAVE -e POSTGRES_USER=$PGUSER -e POSTGRES_PASSWORD=$PGPASS -v $PGDIR2:/var/lib/postgresql/data --link $PGMASTER:db -d postgres
# Now create a table in the master
docker run -it --rm --link $PGMASTER:db -e PGPASSWORD=$PGPASS postgres sh -c "psql -h db $PGNAME -U$PGUSER -c 'create table test (foo int8)'"
# and check it exists in the slave
docker run -it --rm --link $PGSLAVE:db -e PGPASSWORD=$PGPASS postgres sh -c "psql -h db $PGNAME -U$PGUSER -c 'select * from test'"
# and try to insert into the slave???
docker run -it --rm --link $PGSLAVE:db -e PGPASSWORD=$PGPASS postgres sh -c "psql -h db $PGNAME -U$PGUSER -c 'insert into test values (1)'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment