Last post I started hands-on session with PostgreSQL installation on both docker and docker-compose, explored important PostgreSQL configuration and was able to mount persistent volumes and config files to customize PostgreSQL.
In this post I will setup a second PostgreSQL instance to setup a primaty and standby replication for PostgreSQL HA, by using some pg tools, last we will test failover by shut down primary and promot standby instance.
To achieve this, steps can be followed by:
Setup docker network and Create Replication User in Primary instance
To establish PostgreSQL replication, it is necessary to set unique data volumes for data between instances and unique config files for each instance.
Enable Write-Ahead Log, archive and Replication
Write-Ahead Log (WAL) is a PostgreSQL data integrity mechanism of writing transaction logs to file and does not accept the transaction until it has been written to the transaction log and flushed to disk. This ensures that if there is a crash in the system, that the database can be recovered from the transaction log.
So we need to add bellow lines into postgresql.conf to enable Write-Ahead Log and replica and archive
set up standby instance and validate replication
here we need to use tool “pgbase_backup” to create standby instance by taking a primary instance base backup, type “replicationUser” passwd, then postgres-1 database will be back up into postgres-2 pgdata folder
Now, we start the standby instance. See the log below. Postgres-2 is entering standby mode, ready to accept read-only connections, and starting streaming WAL from the primary.
Test replication and failover
First, let us test the replication, by login to postgres-1, create a zack_customers table, then validating from postgres-2
now we simulate failover by using loadbalancer tool “pgctl”, to shut down the primary instance, then promote the standby read-only instance into a read-write instance
Conclusion
Now we are able to run a PostgreSQL primary and standby instances to test replication and failover, in the next blog I will discover how to depoly a single PostgreSQL on kubernetes.