Postgresql

Run docker image

docker run -d --name postgresql -e POSTGRES_PASSWORD=postgres /
-p 5433:5432 --restart=always postgres:10.5

Run postgres slave in docker

Run on master server

echo "host replication all 0.0.0.0/0 md5" >> "$PGDATA/pg_hba.conf"
su postgres
psql
CREATE USER replicate REPLICATION LOGIN CONNECTION LIMIT 100 ENCRYPTED PASSWORD 'kfdjlkj453534532';

Create Dockerfile

FROM postgres:10
RUN apt update
RUN apt install fping -y
COPY ./docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["su", "-c", "postgres", "postgres"]

Create docker-entrypoint.sh

#!/bin/bash
if [ ! -s "$PGDATA/PG_VERSION" ]; then
echo "*:*:*:$PG_REP_USER:$PG_REP_PASSWORD" > ~/.pgpass
chmod 0600 ~/.pgpass
until fping $PG_MASTER
do
echo "Waiting for master to ping..."
sleep 1s
done
until pg_basebackup -h ${PG_MASTER} -p ${PG_MASTER_PORT} -D ${PGDATA} -U ${PG_REP_USER} -vP -W
do
echo "Waiting for master to connect..."
sleep 1s
done

cat >> ${PGDATA}/pg_hba.conf <<EOF
local   all             postgres                                peer
local   all             all                                     trust
host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5
host replication all 0.0.0.0/0 md5
EOF

set -e

cat >> ${PGDATA}/postgresql.conf <<EOF
wal_level = replica
archive_mode = on
archive_command = 'cd .'
max_wal_senders = 8
wal_keep_segments = 8
hot_standby = on
max_connections = 500
EOF

cat > ${PGDATA}/recovery.conf <<EOF
standby_mode = on
primary_conninfo = 'host=$PG_MASTER port=$PG_MASTER_PORT user=$PG_REP_USER password=$PG_REP_PASSWORD'
trigger_file = '/tmp/touch_me_to_promote_to_me_master'
EOF
chown postgres. ${PGDATA} -R
chmod 700 ${PGDATA} -R
fi
exec "$@"

Build and run new docker container

docker build -t my_pg_slave .
docker run -d --name pg_slave -e PG_REP_USER=replicate -e PG_REP_PASSWORD=kfdjlkj453534532 \
-e PG_MASTER=pg-master.blindage.org -e PG_MASTER_PORT=5433 -p 5433:5432 --restart=always my_pg_slave