简体   繁体   English

重新启动容器时使用卷在 postgres docker 上保留数据

[英]Persist data on postgres docker with a volume when restarting the container

I have read stackoverflow posts, but could not found a solution to my problem of persisting data with a volume with postgres:我已阅读 stackoverflow 帖子,但无法找到解决我使用 postgres 使用卷保存数据的问题的解决方案:

First i create a volume:首先我创建一个卷:

docker volume create pgdata

Then i run the postgres container:然后我运行 postgres 容器:

docker run -d -v pgdata:/var/lib/postgresql -e POSTGRES_PASSWORD=password -p 5432:5432 postgres

Then i create a database connecting with sql:然后我创建一个与 sql 连接的数据库:

psql postgresql://postgres:password@localhost:5432/postgres

After stopping the container i restart with:停止容器后,我重新启动:

docker run -d -v pgdata:/var/lib/postgresql -e POSTGRES_PASSWORD=password -p 5432:5432 postgres

The database is lost.数据库丢失。 Should it not stay there, because i use the same volume?它不应该留在那里,因为我使用相同的音量吗?

EDIT: PGDATA="/var/lib/postgresql/data/pgdata" needs to be added and it works as well as the solution of David Maze编辑: PGDATA="/var/lib/postgresql/data/pgdata" 需要添加,它和大卫迷宫的解决方案一样有效

Inside the postgres image , the PostgreSQL data directory is /var/lib/postgresql/data .postgres映像中,PostgreSQL 数据目录是/var/lib/postgresql/data Unless you mount your volume on exactly this path, it won't get used.除非您将卷安装在该路径上,否则它不会被使用。

docker run -d \
  -v pgdata:/var/lib/postgresql/data \ # <-- add .../data
  -e POSTGRES_PASSWORD=password \
  -p 5432:5432 \
  postgres

At a technical level, this is because the Dockerfile declares VOLUME /var/lib/postgresql/data .在技术层面上,这是因为Dockerfile声明了VOLUME /var/lib/postgresql/data If nothing else is mounted on that exact path, this causes Docker to create an anonymous volume at docker run time and store the data there.如果在该确切路径上没有安装其他任何东西,这将导致 Docker 在docker run时创建一个匿名卷并将数据存储在那里。 Since you're mounting a volume on the parent directory but not the exact path, this triggers the anonymous-volume case.由于您在父目录上安装卷而不是确切路径,因此这会触发匿名卷情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM