RomanK
RomanK

Reputation: 47

PostgresDB init in docker-compose

I want init my PostgresDb during starting Docker environment.

docker-compose.yml :

version: '3.1'
services:
  app:
    container_name: springboot-postgresql
    image: sringboot-postgresql
    build:
      context: .
      dockerfile: ./java/Dockerfile
    ports:
    - "8080:8080"
    depends_on:
      - posgresqldb

  posgresqldb:
    image: postgres
    build:
      context: .
      dockerfile: ./pg/Dockerfile
    ports:
    - "5432:5432"
    environment:
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_DB=postgres
    volumes:
      - ./postgres-data:/var/lib/postgresql/data
      - ./pg/init.sql:/docker-entrypoint-initdb.d/init.sql

Dockerfile:

FROM postgres:12-alpine
COPY pg/init.sql /docker-entrypoint-initdb.d/

init.sql:

CREATE USER docker;

CREATE DATABASE postgres;

CREATE TABLE public.usr (
    id varchar NOT NULL,
    username varchar NOT NULL,
    "password" varchar NOT NULL,
    active bool NULL,
    email varchar NULL,
    authorities varchar NULL,
    accountnonexpired bool NULL,
    accountnonlocked bool NULL,
    credentialsnonexpired bool NULL,
    enabled bool NULL,
    CONSTRAINT id_pkey PRIMARY KEY (id)
);

GRANT ALL PRIVILEGES ON DATABASE postgres TO docker;

INSERT INTO public.usr
(id, username, "password", active, email, authorities, accountnonexpired, accountnonlocked, credentialsnonexpired, enabled)
VALUES('1', 'User_1', '*****', false, '', '', false, false, false, false);

init.db mounts succeeds and Docker containers create successfully, but I don't have changes in DB.

enter image description here

Can tou tell me what should I do else. Do I need any additional commands to initialize init.sql?

Thank you.

Upvotes: 3

Views: 1370

Answers (1)

Mihai
Mihai

Reputation: 10727

You don't need to copy the init.sql in Dockerfile since you already mount it inside docker-compose.yml

The container only checks docker-entrypoint-initdb.d if the database is not already initialized. That means the data folder should be empty for the init script to be run.

In your case, make sure the host directory ./postgres-data is empty before you run docker-compose up. As long as data is present in this folder then postgres will use it and not try to initialize the database again.

Upvotes: 3

Related Questions