Load Postgres dump after docker-compose up

2020-05-23 03:09发布

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 <me@me.me>

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 ?

5条回答
孤傲高冷的网名
2楼-- · 2020-05-23 03:19

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!

查看更多
够拽才男人
3楼-- · 2020-05-23 03:20
sudo docker exec postgres psql -U postgres my_db_name < dump.sql
查看更多
等我变得足够好
4楼-- · 2020-05-23 03:25
CONTAINER_NAME="postgres"
DB_USER=postgres
LOCAL_DUMP_PATH="..."
docker run --name "${CONTAINER_NAME}" postgres
docker exec -i "${CONTAINER_NAME}" psql -U "${DB_USER}" < "${LOCAL_DUMP_PATH}"
查看更多
叼着烟拽天下
5楼-- · 2020-05-23 03:31

After the docker-compose up, do docker ps it will give you a list of active docker containers. From that, you can get the container ID.

Then,

docker exec -i {CONTAINER_ID} psql -U {USER} < {.SQL FILE}

查看更多
趁早两清
6楼-- · 2020-05-23 03:35

You can use pg_restore as well ... for example:

cat {BACKUP.SQL.File} | docker exec -i {working_container_name} pg_restore \
--verbose --clean --no-acl --no-owner -U {USER} -d {YOURDATABASE}
查看更多
登录 后发表回答