How To Setup MongoDB In Docker

Introduction

How To Setup MongoDB In Docker
How To Setup MongoDB In Docker

We will go over How To Setup WordPress In Docker.

Did you know that running MongoDB in a docker lets you shield your database from other services?

We will break down this in the following sections:

  • Why running MongoDB in Docker is good
  • How to download and setup MongoDB to run in docker
  • How to keep your MongoDB data persistent

I have used this successfully in various projects, and it works very well and has saved me a ton of trouble and time debugging things.

We will go point by point on getting you up and running in less than 5mins; having some background docker knowledge is helpful if you want to fine-tune your setup, but you don’t need to follow this guide and get started.

This complete guide should cover all your questions on using setting up Docker in MongoDB.

Why Run MongoDB In Docker

You may find yourself asking what is the advantage of running MongoDB inside a docker container. This is a very valid question and the answer has various reasons some of which may or may not apply to you directly. To make this more specific I have assembled a list below. Of course the alternatives is running it natively in your machine/server but this is beyond the scope of this article.

So our list below will be using those two points of reference when comparing things.

  • Since it’s a docker container you can take with you and use it wherever you want
  • You can keep a standard setup and configuration that’s consistent across the board
  • Your pipeline integration later will be a breeze as you’d have everything ready to go and pre-bundled
  • Any third-party dependencies such as MongoDB extensions can be turned only once in your docker container
  • It’s easier to isolate it from the rest of your system applications
  • It’s easier to start/stop and completely turn off or relaunch the container if needed
  • You can easily snapshot your container and go back in time if needed to debug some issue
  • You are guaranteed version consistency in the future if something changes in MongoDB
  • Offers more security as it’s running on its own jail environment

The list above even though it’s not as exhaustive includes some of the reasons why I like to run MongoDB in a docker container.

How To Install Docker

I have detailed this extensively in another article which you can find here:

How To Run Postgres In Docker

How To Get The MongoDB Docker Container

Now that you have successfully installed docker in your system we want to go ahead and fetch the MongoDB docker container for our machine.

The first command we will be issuing is to download the MongoDB docker container from the docker repository. This may require registration and an account in the docker hub which you can do online here.

Once you register and login either from the dashboard which we showed earlier or from the command line using the following command:

$ docker login SERVER_HERE

Now that you have successfully logged on to the docker hub we can go ahead and pull the MongoDB image. The pull command for docker just means to download and register the image as available locally to start working with it. So you can think of it as a combination of two things:

  • Download
  • Register locally

In order to do this we need to specify also the MongoDB docker image which in this case it’s simply mongo. As shown below once you pull the command it will start getting the latest version from the docker hub server.

$ docker pull mongo
Using default tag: latest
latest: Pulling from library/mongo
a749a280e3e9: Already exists
70f92e752512: Already exists
5fdda1347325: Already exists
c5e02463a0f4: Already exists
ff9bc5b0968e: Already exists
33f0d07ad9ca: Already exists
e5c25f5ea983: Already exists
f45978cf40df: Pull complete
f6707d110142: Pull complete
Digest: sha256:6f90d92eb8ed5c52eb602a734697b329a0441949d9bb737ddcd5dae56552cac9
Status: Downloaded newer image for mongo:latest
docker.io/library/mongo:latest

Once the pull is successful you should be able to see the docker MongoDB image in your docker dashboard image registry as shown below.

Setup MongoDB Image
Setup MongoDB Image

Basically this means theMongoDB image is now ready to be used and spawned as a docker container and it was successfully pulled into your machine.

How To Invoke The Docker MongoDB Container

We already covered how to get docker and download your MongoDB container in your system. The next step in the process is running the MongoDB Docker container in your machine. To do this we have to follow a list of steps that we will outline below:

  • Start docker MongoDB container
  • Find the MongoDB Docker IP
  • How to Stop it

How To Start Docker The MongoDB Container

The first step which is what most people call the entry point of the process is to start up our container. To do this we will be leveraging the docker run command along with some parameters which we will explain below. The docker run essentially lets you use an image that you have previously downloaded in our case the MongoDB image and make out of it a container instance. The container instance will be based on the pre-built MongoDB image file.

Lets take a look at the docker run command line attributes that we will be using to start Docker MongoDB in your system.

$ docker run --rm --name mongo -p 27017:27017 -d \
-e MONGO_INITDB_DATABASE=testdb -e MONGO_INITDB_ROOT_USERNAME=user \
-e MONGO_INITDB_ROOT_PASSWORD=mongopass mongo
  • rm: This automatically removes the container if it already exists. It’s useful if you are debugging and want to get rid of older container instances so you can re-use the name among other things. You don’t need to include it if you prune and maintain your containers manually.
  • name: This is simply the name we will be using to refer to the docker container
  • e: This allows us to pass some environment variables that are docker image related. More specifically in the case of the MongoDB docker container we will be using the following ones:
    • MONGO_INITDB_ROOT_USERNAME: This is the username we want our docker MongoDB container to start with, also make a note of this username as you can use it later to connect to it
    • MONGO_INITDB_ROOT_PASSWORD: Similar to above this is the initial password we will be using for the MongoDB docker container instance
    • MONGO_INITDB_DATABASE: This is the name of the MongoDB database we will be creating to host our MongoDB database
  • p: This allows us to bind a specific IP address and port that’s exposed to the rest of the system. It’s useful to interact with the docker container locally for testing things and applications but also to manage it using an admin interface such as MongoDB command line interface
  • d: This demonizes and backgrounds the docker container as soon as it starts
  • Finally we pass on the image name to use to start the docker container instance

Now that we have gone over everything we can go ahead and invoke the run command to see what happens.

$ run-flexer-mongo.sh
f69baeb1aef2a8e9af0eeb83d501867d4a1384e93e7ba9ac7c790560efb299de

As you can see above the run command returns an ID for the docker container instance. Using this ID you can identify this particular container and be able to use to maintain and connect to the instance.

To verify the instance started and it’s in a good state we will be using the docker ps command. The docker ps command is very similar to the UNIX ps command it basically lets you list the running docker container instances. From the execution below we can see what’s running in our system.

$ docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                      NAMES
f69baeb1aef2   mongo     "docker-entrypoint.s…"   44 seconds ago   Up 43 seconds   0.0.0.0:27017->27017/tcp   mongo

We know our invocation succeeded because we can see our abbreviated version of our container ID matching the one we started. Furthermore, the STATUS for the container is showing that it’s been up for 3 seconds and it’s functioning properly.

How To Find MongoDB Docker IP Address

The next step we want to do is find out what IP address we have allocated internally so we can connect to it. To do this we will be using the docker inspect command to find the docker MongoDB IP address. The invocation is as simple as running docker inspect followed by the docker container ID we received previously. To avoid going through the long output of the command we will pipe this to a grep that looks specifically for the IP address of the instance. Putting it all together and invoking is shown below.

$ docker inspect f69baeb1aef2 |grep -i ipaddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",

The IP for our MongoDB container is:

  • MongoDB -> 172.17.0.2

Using this internally you can connect to the instance, but we also exposed the port to it into the localhost so you can directly connect via the local IP address too.

How To Stop MongoDB Docker Container

Finally, we will go over how to stop the MongoDB docker containers. In order to do this, we will be using the container command which has a sub-command called stop. That subcommand essentially lets us give it a container ID parameter and basically stop it. However, there’s an extra step we need to follow here which is a clean-up process. If we do not intend to re-use that docker container we need to make sure we prune it from our system so it remains clean. If we fail to do this every run will create a new docker container and eventually our system will get flooded with a big list of them.

$ docker container stop $(docker container ls -q --filter name=mongo)
f69baeb1aef2

$ docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

$ docker container prune
WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
Total reclaimed space: 0B

Lets go over what we did above and explain things a bit.

  • We use the docker container stop command to invoke a stop of the running container, however that command requires a docker container ID
  • To solve the problem above we cascade the command with the docker container filtering by name as shown. That command allows us to find an ID from a container name, in this case mongo
  • Finally we verify that nothing is running by using docker ps which is shown to return empty
  • As a cleanup we run the prune command to remove all stopped containers and save some space

How To Keep MongoDB Data Persistent

As a bonus I want to cover a way to make your data persistent across your docker runs. After all a database is only useful if the data persists across reboots, starting and stopping.

Docker offers a feature that lets you expose a predefined directory by binding it to the docker container. This directive essentially makes the data persist outside the docker environment which is destroyed and recreated every time you start and stop it. In the examples we provided earlier we did not cover one of the options shown which was -v, below I explain why this is useful and how it solves our problem of persistency.

In order to do this we need to append an additional parameter in our docker run command using the -v parameter. This would look like this:

-v /HOST_PATH:/CONTAINER_PATH

There’s two important paths here that we need to adjust based on your installation and system:

  • HOST_PATH: This is basically the path in your host operating system (Mac/windows/linux) that contains the data you want. In our case we can use a simply empty directory so feel free to make this anywhere the docker instance has permissions on and point it to it.
  • CONTAINER_PATH: This is basically the path where your MongoDB stores the data on. Based on your configuration this needs to be adjusted accordingly. By data I mean where the data folder for your database is inside the docker container.

More specifically for our examples these are the directory mappings you need to make for the default data to persist.

-v mongo-disk:/data/db

The default directory above is used by MongoDB.

Once you do this and start your instance you should have all your data persist across installations and you can freely tear down and restart your docker MongoDB container.

Conclusion

If you found How To Setup MongoDB In Docker useful and you think it may have helped you please drop me a cheer below I would appreciate it.

If you have any questions, comments please post them below I check periodically and try to answer them in the priority they come in. Also if you have any corrections please do let me know and I’ll update the article with new updates or mistakes I did.

Do you dockerize your databases?

I personally like to keep my setup in containers to avoid installing things natively and to have more security layers in my system. Also I like to have fine control on starting and stopping services as needed.

If you would like to learn more about docker-related stuff, I have a few articles below:

You can find more information on docker here:

You can find more information on Mongo here:

Leave a Comment

Your email address will not be published. Required fields are marked *