如何使用卷将数据保存在 dockerized postgres 数据库中 [英] How to persist data in a dockerized postgres database using volumes
问题描述
我的 docker compose 文件有三个容器,web、nginx 和 postgres.Postgres 看起来像这样:
My docker compose file has three containers, web, nginx, and postgres. Postgres looks like this:
postgres:
container_name: postgres
restart: always
image: postgres:latest
volumes:
- ./database:/var/lib/postgresql
ports:
- 5432:5432
我的目标是在 postgres 容器内挂载一个与名为 ./database
的本地文件夹相对应的卷,作为 /var/lib/postgres
.当我启动这些容器并将数据插入 postgres 时,我验证 /var/lib/postgres/data/base/
是否充满了我添加的数据(在 postgres 容器中),但在我的本地系统,./database
只在其中获取一个data
文件夹,即创建了./database/data
,但它是空的.为什么?
My goal is to mount a volume which corresponds to a local folder called ./database
inside the postgres container as /var/lib/postgres
. When I start these containers and insert data into postgres, I verify that /var/lib/postgres/data/base/
is full of the data I'm adding (in the postgres container), but in my local system, ./database
only gets a data
folder in it, i.e. ./database/data
is created, but it's empty. Why?
注意事项:
根据 Nick 的建议,我做了一个 docker inspect
并发现:
Per Nick's suggestion, I did a docker inspect
and found:
"Mounts": [
{
"Source": "/Users/alex/Documents/MyApp/database",
"Destination": "/var/lib/postgresql",
"Mode": "rw",
"RW": true,
"Propagation": "rprivate"
},
{
"Name": "e5bf22471215db058127109053e72e0a423d97b05a2afb4824b411322efd2c35",
"Source": "/var/lib/docker/volumes/e5bf22471215db058127109053e72e0a423d97b05a2afb4824b411322efd2c35/_data",
"Destination": "/var/lib/postgresql/data",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
],
这使得数据看起来像是被另一个我没有编写代码的卷窃取了.不知道为什么会这样.postgres 图像是否为我创建了该卷?如果是这样,是否有某种方法可以使用 那个卷 而不是我在重新启动时安装的卷?否则,是否有禁用其他卷并使用我自己的 ./database
的好方法?
Which makes it seem like the data is being stolen by another volume I didn't code myself. Not sure why that is. Is the postgres image creating that volume for me? If so, is there some way to use that volume instead of the volume I'm mounting when I restart? Otherwise, is there a good way of disabling that other volume and using my own, ./database
?
我找到了解决方案,感谢尼克!(和另一个朋友)在下面回答.
I found the solution, thanks to Nick! (and another friend) Answer below.
推荐答案
奇怪的是,解决方案最终是改变
Strangely enough, the solution ended up being to change
volumes:
- ./postgres-data:/var/lib/postgresql
到
volumes:
- ./postgres-data:/var/lib/postgresql/data
这篇关于如何使用卷将数据保存在 dockerized postgres 数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!