Docker is rapidly gaining popularity as it makes lightweight Linux containers easy to use, among other things. If you’re new to Docker, wondering how it is different from virtual machines and what benefits it provides, check this out first.

This blog post series will walk through step-by-step how to best use MongoDB on Docker, from simple single-process development/test setups to more complex multi-host production replica set setups, with thoughts on log management, performance, data persistence, etc.

Virtual Machines (VMs) vs Docker containers.

Virtual Machines (VMs) vs Docker containers.


There are plenty of online resources out there already talking about MongoDB on Docker, but most seem to be based on Ubuntu and describe only single host setups that are not ideal for production usage (e.g. docs, this and that blog post). Nothing against Ubuntu (or Debian), but I figured it will be useful to have some examples with RPM-based Linux distros such as Fedora/RHEL and openSUSE/SLES. So let’s begin with a simple Dockerfile based on the latest version of CentOS (version 7 at this time of writing):

Then create the following file mongodb.repo in the same directory:

We can now build our Docker image by running docker build -t mongod . in the terminal, with the current directory containing the two files above. The first run will take a while as the dependencies (e.g. CentOS, MongoDB) are downloaded and installed. Subsequent runs are fast as each command/stage is cached; thus if nothing changed it is basically instant. For example:

Run docker images to see that there is now a “mongod” image/repository. For example:

Start the freshly built image by running docker run -d -P mongod --smallfiles. Run docker ps to see currently running containers and the mapped ports. For example:

View the logs (e.g. STDOUT) of the container by running docker logs CONTAINER_ID. For example:

From the docker ps output, we can see that the “exposed” default mongod port 27017 in the container is mapped to port 49155 on the Docker host (which is localhost in my case as I’m on Linux and running Docker directly). Thus, I can connect to the mongod process in the container by running mongo --port 49155. For example:

That’s it for now. We’ll investigate the various Docker networking options and their trade-offs in the next post.