How to persist MongoDB data between container restarts?

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.


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.

Tags:

Docker

Mongodb