Docker for Developers — MongoDB

Alon Valadji
2 min readJul 17, 2018

--

As developers we are often struggle to install our environment and configure it, just to run our database locally.

This frustration task can be much more efficient using docker.

You can download a copy of docker for your os here: https://www.docker.com/community-edition#/download

So to run a docker image of mongo all we have to do is run this follow command:

docker run mongo

If you have the image locally it will run MongoDB, if not it will download the image and then run it, however you won’t be able to connect it as we need to map it to our local port.

To do so we need to add-p switch argument to docker run:

docker run -p 27017:27017 mongo

The first number is the port on your local machine, the second, after the semi-column, is the port that MongoDB is running on the container.

Now the container will run and bind it to your local port of 27017, so you can connect to mongodb://localhost:27017.

But what about persistent? We are losing our data every time we stop the container.

Docker has a — -mount or -v switch argument which allows you to connect a local folder to the running container:

docker run -d -v $PWD/data/bin:/data/bin mongo

The -d switch is telling docker to run as detached so MongoDB will run in the background. The -v switch accepts, first, an absolute path to your local folder and after the semi-column the path to the folder on the container. MongoDB files are stored by default at /data/bin.

Let’s see the same command with — -mount which is the encouraged command to use as it supports more use cases:

docker run -d --mount type=bind,source=$PWD/data/bin,destination=/data/bin mongo

Now your data will be kept when you stop the docker container.

It is also very useful to keep it in your current project folder and not in a global folder, as now you can use different project using MongoDB with same db names but you will have the appropriate data and no conflicts.

So we have managed to remove away some distractions within our development process. Hope it was helpful for you.

I would be happy to hear your comments or remark on this to improve future posts. Thanks for reading.

More where this came from

This story is published in Noteworthy, where thousands come every day to learn about the people & ideas shaping the products we love.

Follow our publication to see more product & design stories featured by the Journal team.

--

--

Alon Valadji

Alon is a leading software architect well-versed in Rozansky and Woods’ architectural methodologies. As a full-cycle JavaScript and web architecture torchbearer