mongodbdocker

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.


Solution

  • 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