如何使用卷将数据持久化在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?
注意:
- This suggests my above file should work.
- This person is using docker services which is interesting
根据尼克的建议,我做了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屋!