Skip to content

Instantly share code, notes, and snippets.

@songpon
Last active November 23, 2018 07:09
Show Gist options
  • Save songpon/26a53884eaab850242e4d331f303bb0a to your computer and use it in GitHub Desktop.
Save songpon/26a53884eaab850242e4d331f303bb0a to your computer and use it in GitHub Desktop.
#!/bin/bash
MASTER_IP=
SLAVE_IP=
# service postgresql stop
su - postgres
psql -c "CREATE ROLE replica WITH PASSWORD 'myreplpassword' LOGIN REPLICATION;"
#Security for master allow standby access
echo "host replication replica $SLAVE_IP/32 md5" >> /etc/postgresql/10/main/pg_hba.conf
# Postgres Master config
cat <<EOT >> /etc/postgresql/10/main/postgresql.conf
listen_addresses = '*'
wal_level = replica
max_wal_senders = 5
wal_keep_segments = 32
archive_mode = on
archive_command = 'cp %p /var/lib/postgresql/10/main/archive/%f'
synchronous_commit = local
EOT
mkdir -p /var/lib/postgresql/10/main/archive/
chmod 700 /var/lib/postgresql/10/main/archive/
chown -R postgres:postgres /var/lib/postgresql/10/main/archive/
# service postgresql start
#########################
# Standby server config
su - postgres
echo "$MASTER_IP:*:*:replica:myreplpassword" > ~/.pgpass
chmod 600 ~/.pgpass
# service postgresql stop
# clear old db by rename
mv /var/lib/postgresql/10/main /var/lib/postgresql/10/main.bak
#inital download database from master
pg_basebackup -h $MASTER_IP -D /var/lib/postgresql/10/main -P -R -U replica
echo "hot_standby = on" >> /etc/postgresql/10/main/postgresql.conf
cat <<EOT >> /var/lib/postgresql/10/main/recovery.conf
trigger_file = '/tmp/postgresql.trigger.5432'
restore_command = 'cp /var/lib/postgresql/10/main/archive/%f %p'
archive_cleanup_command = 'pg_archivecleanup /var/lib/postgresql/10/main/archive %r'
recovery_target_timeline = 'latest'
EOT
# service postgresql start
# check standby server for standby mode
# tail -f /var/log/postgresql/postgresql-10-main.log
# references
# https://dba.stackexchange.com/questions/158901/creating-a-hot-standby-with-postgres-9-6/159035
# https://blog.2ndquadrant.com/evolution-of-fault-tolerance-in-postgresql-replication-phase/
# https://www.howtoforge.com/tutorial/how-to-set-up-master-slave-replication-for-postgresql-96-on-ubuntu-1604/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment