How to initialize a PSQL database in docker-compose file?

albertoivo picture albertoivo · Nov 6, 2018 · Viewed 6.9k times · Source

I would like to know if it's possible to execute a PSQL command inside the docker-compose file.

I have the following docker-compose.yml:

version: '3' 
services:
  postgres:
    image: postgres:9.6
    container_name: postgres-container
    ports:
      - "5432:5432"
    network_mode: host
    environment:
      - LC_ALL=C.UTF-8
      - POSTGRES_DB=databasename
      - POSTGRES_USER=username
      - POSTGRES_PASSWORD=
      - POSTGRES_PORT=5432

And After this is running ok, I run the following command: docker exec -i postgres-container psql -U username -d databasename < data.sql

These 2 steps works fine. But I would ike to know if it's possible to make one single step.

Every time I want to run this command. It's important the database is always new. That's why I don't persist it in a volume and want to run this command.

Is it possible to run docker-compose up and also run the psql command?

Thanks in advance!

Answer

Siyu picture Siyu · Nov 6, 2018

Pure docker-compose solution with volume,

  volumes:
    - ./data.sql:/docker-entrypoint-initdb.d/init.sql

According to the dockerfile, at start up, it will dump in every sql data in docker-entrypoint-initdb.d