[英]How to persist MongoDB data between container restarts?
It is quite easy to run MongoDB containerised using docker.使用 docker 运行容器化的 MongoDB 非常容易。 Though each time you start a new mongodb container, you will get new empty database.
尽管每次启动一个新的 mongodb 容器时,您都会获得新的空数据库。
What should I do in order to keep the database content between container restarts?我应该怎么做才能在容器重新启动之间保持数据库内容? I tried to bind external directory to container using -v option but without any success.
我尝试使用 -v 选项将外部目录绑定到容器,但没有成功。
I tried using the ehazlett/mongodb
image and it worked fine.我尝试使用
ehazlett/mongodb
图像,效果很好。
With this image, you can easily specify where mongo store its data with DATA_DIR env variable.使用此图像,您可以使用 DATA_DIR 环境变量轻松指定 mongo 存储其数据的位置。 I am sure it must not be very difficult to change on your image too.
我相信改变你的形象一定不是很困难。
Here is what I did:这是我所做的:
mkdir test; docker run -v `pwd`/test:/tmp/mongo -e DATA_DIR=/tmp/mongo ehazlett/mongodb
notice the `pwd`
in within the -v
, as the server and the client might have different path, it is important to specify the absolute path.注意
-v
的`pwd`
,因为服务器和客户端可能有不同的路径,指定绝对路径很重要。
With this command, I can run mongo as many time as I want and the database will always be store in the ./test
directory I just created.使用此命令,我可以根据需要多次运行 mongo,并且数据库将始终存储在我刚刚创建的
./test
目录中。
When using the official Mongo docker image, which is ie version mongo:4.2.2-bionic
as writing this answer, and using docker-compose, you can achieve persistent data storage using this docker-compose.yml
file example.当使用官方的 Mongo docker 镜像,即版本
mongo:4.2.2-bionic
作为写这个答案,并使用 docker-compose 时,您可以使用这个docker-compose.yml
文件示例实现持久化数据存储。
root
directory in the folder /data/db
by default./data/db
文件夹下root
目录下的容器中。data
(in this example).data
的文件夹(在本例中)。27017-27019:27017-27019
.27017-27019:27017-27019
。 Example of my docker-compose.yml
:我
docker-compose.yml
:
version: "3.2"
services:
mongodb:
image: mongo:4.2.2-bionic
container_name: mongodb
restart: unless-stopped
ports:
- 27017-27019:27017-27019
volumes:
- ./data:/data/db
Run docker-compose up
in the directory where the yml
file is located to run the mongodb
container with persistent storage.在
yml
文件所在目录运行docker-compose up
,运行具有持久化存储的mongodb
容器。 If you do not have the official image yet, it will pull it from Dockerhub first.如果你还没有官方镜像,它会先从 Dockerhub 拉取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.