Vladimir Lebedev
Vladimir Lebedev

Reputation: 1237

How to persist MongoDB data between container restarts?

It is quite easy to run MongoDB containerised using docker. Though each time you start a new mongodb container, you will get new empty database.

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.

Upvotes: 17

Views: 9434

Answers (3)

zergius
zergius

Reputation: 434

Old post but may be someone still need quick and easy solution... The easiest way I found is using binding to volume. Following that way you can easily attach existing MongoDB data; and it will live even after you destroying the container.

  1. Create volume that points to your folder (may include existing db). In my case it's done under Windows, but you can do it on any file system:
    docker volume create --opt type=none --opt o=bind --opt device=d:/data/db db
  1. Create/run docker container with MongoDB using that volume binding:
    docker run --name mongodb -d -p 27017:27017 -v db:/data/db mongo

Upvotes: 4

HelloBlob
HelloBlob

Reputation: 451

When using the official Mongo docker image, which is i.e. 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.

  • In the official mongo image, data is stored in the container under the root directory in the folder /data/db by default.
  • Map this folder to a folder in your local working directory called data (in this example).
  • Make sure ports are set and mapped, default 27017-27019:27017-27019.

Example of my 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. If you do not have the official image yet, it will pull it from Dockerhub first.

Upvotes: 10

creack
creack

Reputation: 121732

I tried using the ehazlett/mongodb image and it worked fine.

With this image, you can easily specify where mongo store its data with DATA_DIR env variable. 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.

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.

Upvotes: 8

Related Questions