/docker-postgres-replication

Postgres streaming replication with Docker containers

Primary LanguageShell

Postgres Streaming Replication

Enhanced version of the official Postgres image to support streaming replication out of the box.

Postgres-replication is meant to be used with orchestration systems such as Kubernetes.

Tags

Images are automatically updated when the official postgres image is updated.

Supported tags:

Run with Docker Compose

docker-compose up

Then you can try to make somes changes on master

docker exec -it docker-postgres-replication_postgres-master_1 psql -U postgres
postgres=# create database test;
postgres=# \c test
test=# create table posts (title text);
test=# insert into posts values ('it works');

Then changes will appear on slave

docker exec docker-postgres-replication_postgres-slave_1 psql -U postgres test -c 'select * from posts'
  title
----------
 it works
(1 row)

Exemple of docker-compose.yml

version: "3.3"
services:
  postgres:
    image: madeindjs/postgres-replication:12.3
    shm_size: "2gb"
    environment:
      POSTGRES_USER: madeindjs
      POSTGRES_PASSWORD: password
      REPLICATION_USER: madeindjs_rep
      REPLICATION_PASSWORD: password
    ports:
      - 5432:5432
    expose:
      - 5432

  postgres-slave:
    image: madeindjs/postgres-replication:12.3
    links:
      - postgres
    environment:
      POSTGRES_USER: madeindjs
      POSTGRES_PASSWORD: password
      REPLICATION_USER: madeindjs_rep
      REPLICATION_PASSWORD: password
      REPLICATION_ROLE: slave
      POSTGRES_MASTER_SERVICE_HOST: postgres
    expose:
      - 5432
    depends_on:
      - postgres

Run with Docker

To run with Docker, first run the Postgres master:

docker run -p 127.0.0.1:5432:5432 --name postgres-master madeindjs/postgres-replication

Then Postgres slave(s):

docker run -p 127.0.0.1:5433:5432 --link postgres-master \
           -e POSTGRES_MASTER_SERVICE_HOST=postgres-master \
           -e REPLICATION_ROLE=slave \
           -t madeindjs/postgres-replication

Notes

Replication is set up at container start by putting scripts in the /docker-entrypoint-initdb.d folder. This way the original Postgres image scripts are left untouched.

See Dockerfile and official Postgres image for custom environment variables.