postgresql 在 docker-compose up 后加载 Postgres 转储
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36781984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load Postgres dump after docker-compose up
提问by jood
I have a dump.sql file that I would like to load with docker-compose.
我有一个 dump.sql 文件,我想用 docker-compose 加载它。
docker-compose.yml:
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:
我的 Dockerfile.db 目前非常简单:
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.
我想psql my_db_name < dump.sql
在某个时候运行一个命令。如果我从 Dockerfile.db 运行这样的脚本,问题是脚本在 build 之后但之前运行docker-compose up
,并且数据库尚未运行。
Any idea how to do this ?
知道如何做到这一点吗?
回答by jood
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.
阅读https://hub.docker.com/_/postgres/,“扩展此映像”部分说明 /docker-entrypoint-initdb.d 中的任何 .sql 将在构建后执行。
I just needed to change my Dockerfile.db to:
我只需要将我的 Dockerfile.db 更改为:
FROM postgres
ADD ./devops/db/dummy_dump.sql /docker-entrypoint-initdb.d
And it works!
它有效!
回答by Valentin Kantor
sudo docker exec postgres psql -U postgres my_db_name < dump.sql
回答by Milso
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}"
回答by Prashantkumar K B
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.
在 docker-compose up 之后,执行 docker ps 它会给你一个活动 docker 容器的列表。从中,您可以获取容器 ID。
Then,
然后,
docker exec -i {CONTAINER_ID} psql -U {USER} < {.SQL FILE}
docker exec -i {CONTAINER_ID} psql -U {USER} < {.SQL FILE}
回答by porto
You can use pg_restore as well ... for example:
您也可以使用 pg_restore ......例如:
cat {BACKUP.SQL.File} | docker exec -i {working_container_name} pg_restore \
--verbose --clean --no-acl --no-owner -U {USER} -d {YOURDATABASE}