Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Postgres dump after docker-compose up

I have a dump.sql file that I would like to load with docker-compose.

docker-compose.yml:

services:
  postgres:
    environment:
      POSTGRES_DB: my_db_name
      POSTGRES_USER: my_name
      POSTGRES_PASSWORD: my_password
    build:
      context: .
      dockerfile: ./devops/db/Dockerfile.db

My Dockerfile.db is really simple at the moment:

FROM postgres
MAINTAINER me <[email protected]>

COPY ./devops/db ./devops/db
WORKDIR ./devops/db

I would like to run a command like psql my_db_name < dump.sql at some point. If I run a script like this from the Dockerfile.db, the issue is that the script is run after build but before docker-compose up, and the database is not running yet.

Any idea how to do this ?

like image 491
jood Avatar asked Apr 21 '16 23:04

jood


People also ask

Which is the command to reload compressed Postgres dump?

I used the "psql -d database_name -f backup. sql" command to restore a database I dumped from dokku on DigitalOcean. Worked great. while using psql if your user (for e.g. postgres ) has a password set then -W option should be used.


2 Answers

Reading https://hub.docker.com/_/postgres/, the section 'Extend this image' explains that any .sql in /docker-entrypoint-initdb.d will be executed after build.

I just needed to change my Dockerfile.db to:

FROM postgres

ADD ./devops/db/dummy_dump.sql /docker-entrypoint-initdb.d

And it works!

like image 100
jood Avatar answered Sep 27 '22 06:09

jood


Another option that doesn't require a Dockerfile would be to mount your sql file into the docker-entrypoint-initdb.d folder using the volumes attribute of docker-compose. The official postgres image https://hub.docker.com/_/postgres/ will import and execute all SQL files placed in that folder. So something like

services:
  postgres:
    environment:
      POSTGRES_DB: my_db_name
      POSTGRES_USER: my_name
      POSTGRES_PASSWORD: my_password
  volumes:
    - ./devops/db/dummy_dump.sql:/docker-entrypoint-initdb.d/dummy_dump.sql

This will automatically populate the specified POSTGRES_DB for you.

like image 17
emilaz Avatar answered Oct 01 '22 06:10

emilaz