Posted on 10 Jul 2018
This is the fifth article of the Getting started with Docker series. In this article, I am going to show how to install a PostgreSQL cluster on three Docker containers.
The cluster will be configured in master/slave mode with one master and two slaves. PostgreSQL supports two cluster type: hot and warm standby. The former allows the slave to receive connections in read-only, the latter doesn’t allow the slaves to receive connections. In this tutorial, we will configure the cluster as hot standby.
The first step to create a PostgreSQL cluster is to modify the start_containers.sh script to create two environment variables that we pass to the docker create command.
These variables will be used by the startup scripts to start the master and the two slaves.
The two environment variables defined in the previous section will be used by the startup scripts to understand if the container contains the master of one of the two slaves.
Here the code of the src/postgresql/entrypoint.sh script. We added a sleep command for slave nodes.
Here the code of the src/postgresql/bin/entrypoint.sh script.
The code checks whether the data directory is empty or not. In the latter case, the code assumes the data directory already exists and then we only startup PostgreSQL. In the former case, the code is different for the master and slaves.
For the master, the code is similar to the previous article. The data directory is initialized and the configuration files postgresql.conf and pg_hba.conf are copied in it.
For the slaves, the code will wait for the master is up and running and then they replicate the data directory from it with the pg_basebackup command. Finally, we copy the recovery.conf file and let it refers to the master node.
To configure the PostgreSQL cluster as hot standby we need to uncomment the following lines in the postgresql.conf file.
In the pg_hba.conf we will specify the host from which the replication is allowed.
An easy way to verify if the cluster is working is to create a database on the master node and verify its replication on slaves. Run the following commands on the master node.
Verify on slave nodes if the database has been replicated using the following commands. To verify the database is replicated on node3 use the same commands and replace 5433 port with 5434.
In this article, we learned how to use the three containers created in the previous article to install a PostgreSQL cluster. You can download the source code here in the postgresql-cluster folder. In the next article, we will discuss another important Docker concept: volumes.