Using MongoDB on Docker

Using MongoDB on Docker

Installing MongoDB is difficult and time-consuming and requires many configuration changes. All this process can be made easy by using MongoDB over Docker.

Here is a short and simple tutorial that I wrote for myself and sharing here. I'm using Kali Linux 20.04. It should be similar for all other OS.

Depending on how docker is configured on your system you might need to use sudo before all the docker commands

Step 1: Pull docker image of MongoDB

docker pull mongo

The MongoDB image will be downloaded.

Check the list of docker images

docker images Screenshot from 2021-01-30 20-31-06.png

Step 2: Create a container

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

In /data/db:/data/db, the first part in the path where the data is stored on you system(change this if required). The 2nd part is the path where the data is saved by MongoDB inside the container.

The container mongo_cont should be running. Check the list of containers. Make sure port 27017 is not occupied already.

docker ps -a

Screenshot from 2021-01-30 20-38-32.png

Step 3: Get into the container to use mongo shell

docker exec -it <CONTAINER ID> bash

Now you are inside the container. Open mongo shell in the container using:-


Screenshot from 2021-01-30 20-59-13.png

- Stopping the container

docker stop <CONTAINER ID>

- Starting the container again after stopping and using it again

docker start <CONTAINER ID>

docker exec -it <CONTAINER ID> bash

Some important points:-

  • All the containers have the same databases
  • Stopping the container doesn't delete the database data
  • Restarting the system doesn't delete the database data
  • Deleting the container doesn't delete the database data. When a new container is created the previous data is present in it.