使用MongoDB docker映像停止VM而不丢失数据 [英] Stop VM with MongoDB docker image without losing data

查看:627
本文介绍了使用MongoDB docker映像停止VM而不丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在AWS EC2上的VM中安装了官方的MongoDB docker映像,并且数据库上已经有数据.如果我停止VM(以节省过夜费用),是否会丢失数据库中包含的所有数据?在这些情况下如何使它持久?

I have installed the official MongoDB docker image in a VM on AWS EC2, and the database has already data on it. If I stop the VM (to save expenses overnight), will I lose all the data contained in the database? How can I make it persistent in those scenarios?

推荐答案

有多种方法可以实现此目的,但最常见的2种方法是:

There are multiple options to achieve this but the 2 most common ways are:

  • 在主机上创建目录以装入数据
  • 创建一个码头工人 卷以装载数据
  • Create a directory on your host to mount the data
  • Create a docker volume to mount the data

1)在主机系统上的适当卷上创建一个数据目录,例如/my/own/datadir.像这样启动您的mongo容器:

1) Create a data directory on a suitable volume on your host system, e.g. /my/own/datadir. Start your mongo container like this:

$ docker run --name some-mongo -v /my/own/datadir:/data/db -d mongo:tag

命令的-v /my/own/datadir:/data/db部分将基础主机系统中的/my/own/datadir目录作为/data/db挂载在容器内,默认情况下,MongoDB将在其中写入其数据文件.

The -v /my/own/datadir:/data/db part of the command mounts the /my/own/datadir directory from the underlying host system as /data/db inside the container, where MongoDB by default will write its data files.

请注意,启用了SELinux的主机系统上的用户可能会看到与此相关的问题.当前的解决方法是将相关的SELinux策略类型分配给新的数据目录,以便允许容器访问它:

$ chcon -Rt svirt_sandbox_file_t /my/own/datadir

此来源是图片的官方文档.

2)另一种可能性是使用docker卷.

2) Another possibility is to use a docker volume.

$ docker volume create my-volume

这将在文件夹/var/lib/docker/volumes/my-volume中创建一个docker卷.现在,您可以使用以下内容启动容器:

This will create a docker volume in the folder /var/lib/docker/volumes/my-volume. Now you can start your container with:

docker run --name some-mongo -v my-volume:/data/db -d mongo:tag

所有数据将存储在my-volume中,因此将存储在文件夹/var/lib/docker/my-volume中.因此,即使您删除容器并创建与此卷链接的新mongo容器,您的数据也将被加载到新容器中.

All the data will be stored in the my-volume so in the folder /var/lib/docker/my-volume. So even when you delete your container and create a new mongo container linked with this volume your data will be loaded into the new container.

在执行初始的docker run命令时,也可以使用--restart=always选项.这意味着您的容器将在VM重新引导后自动重新启动.持久化数据后,重启之前或之后的数据库之间也不会有任何区别.

You can also use the --restart=always option when you perform your initial docker run command. This mean that your container automatically will restart after a reboot of your VM. When you've persisted your data too there will be no difference between your DB before or after the reboot.

这篇关于使用MongoDB docker映像停止VM而不丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆