Reputation: 1237
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
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.
docker volume create --opt type=none --opt o=bind --opt device=d:/data/db db
docker run --name mongodb -d -p 27017:27017 -v db:/data/db mongo
Upvotes: 4
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.
root
directory in the folder /data/db
by default. data
(in this example). 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
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