Running MongoDB in a Docker Container

Rishabh Sharma
3 min readFeb 23, 2022


MongoDB is of the most popular databases. It is cross-platform ,easily scalable and gives high performance. It is NoSQL database and works on the concept of collection and document.

Collection- Collection in MongoDB is a group of MongoDB Documents. (Equivalent to Table of SQL databases).

Document- It is a set of key-value pair. It does not depend on a schema , it is dynamic.

Docker is a container management service which makes it easier for the people across the team to work harmoniously and within the similar environment keeping everyone on the same page. A Docker container can be thought of as a single unit containing an application and all of the necessary configuration and dependency.

Now , MongoDB can be directly installed on your local machine or it can be installed in a container on the docker.

First of all we need to install Docker. Here I am doing it on windows.

Download Docker for windows from official website.

Install it and you may be prompted to install WSL2 . Download WSL2 from here.

To check if docker is properly installed type docker — version in cmd.

Check Docker Version

Now to run MongoDB in a container we need to pull MongoDB image from docker hub.

But first of all we need to create a volume so that data is persistent even after the container stops. To create volume -

First of all go into the directory where you want to store the data and run the command (Can change the name of the data volume -here I have used mongodata).

docker volume create --name=mongodata
Volume is created for MongoDB.

Next we pull the MongoDB image from Docker Hub by using

docker run --name mongodb -v mongodata:/data/db -d -p 27017:27017 mongo

As default MongoDB port is 27017 so we have mapped our port 27017 to the MongoDB image’s port 27017.

MongoDB image pulled from Docker Hub.

To check the status of the image

docker ps -a
Currently MongoDB image is running

Container id of my mongo container starts from 0f0c…

So to execute the MongoDB container we write

docker exec -it 0f0 bash //replace 0f0 with your container id initials.
Executing the MongoDB image.

To check that we have successfully installed Mongo image we type mongo in the shell.

You will get the mongo version if you have successfully installed Mongo image.

Thanks for reading. Hope it was helpful.