3

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Cleaning up ./postgres-data helped me to solve this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.