Initialise Postgresql Container with init SQL script


Initialise Postgresql Container with init SQL script

Initialise Postgresql Container with init SQL script

Prerequisite

  1. Install Docker
  2. Install docker-compose

Init SQL script with postgresql container

PostgreSQL

  • Create a docker-compose.yml with the following
---
version: '3'
services:
  postgresql:
    image: postgres:12.3
    container_name: postgres
    volumes:
      # Uncomment below to maintain the persistent data
      - ct-data:/var/lib/postgresql/data/
      # Uncomment bellow to initialize the container with data by creating the respective file
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    environment:
      - POSTGRES_USER=postgress
      - POSTGRES_PASSWORD=postgress
    ports: ['5432:5432']
    networks: ['stack']
    healthcheck:
      test: curl -s https://localhost:5432 >/dev/null; if [[ $$? == 52 ]]; then echo 0; else echo 1; fi
      interval: 30s
      timeout: 10s
      retries: 5
  adminer:
    image: adminer
    container_name: adminer
    restart: always
    ports: ['8080:8080']

volumes:
  ct-data:
networks:
  stack:

Try in PWD

  • Create an init.sql with the following
CREATE USER postgress WITH PASSWORD 'postgress';
CREATE DATABASE pdata;
GRANT ALL PRIVILEGES ON DATABASE pdata TO ct;

CREATE SEQUENCE IF NOT EXISTS recipient_seq
    START WITH 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;

CREATE TABLE IF NOT EXISTS recipient
(
    id                      BIGINT                   NOT NULL,
    recipient_id            VARCHAR(255)             NOT NULL,
    first_name              VARCHAR(255)             NOT NULL,
    middle_name             VARCHAR(255)             NOT NULL,
    last_name               VARCHAR(255)             NOT NULL,
    CONSTRAINT recipient_pk PRIMARY KEY (id)
);
  • Run the container with docker-compose up -d. This starts PostgreSQL and initializes the database with the above scripts.

See that it’s working

docker logs -f postgres

# OR

docker logs postgres