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.
If you want to persist the data on your local machine, you can mount a volume using the -v argument. If your application is running inside a container itself, you can run MongoDB as part of the same Docker network as your application using --network .
By default, the MongoDB container stores the databases within the /data/db directory within the container. Next, we need to create a directory called “mongodb” to hold the docker-compose file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With