How to create a MongoDB Docker container

Responsive image
0 Comments         7936 Views

Here we have described the procedures to create a docarized MongoDB container along with all the necessary commands.

We are assuming you have installed docker in your PC and you have the basic knowledge of docker. If you don't have installed docker then please take a look at the following link and install docker into you PC. 

https://docs.docker.com/engine/install/

Follow the following steps to create a mongodb container

1. Full the mongo image from the docker hub:
sudo docker pull mongo:4.4.3

2. By the following command you can see the pulled MongoDB docker image in your PC.
sudo docker images

3. Create a /mongodata directory on the host system:
sudo mkdir -p /mongodata

4. Run the mongodb container:
sudo docker run -it -v mongodata:/data/db -p 27018:27017 --name mongodb -d mongo:4.4.3

By default, docker container keeps mongo database's data in /data/db location. See below the details of the above command.

-it – Provides an interactive shell to the Docker container.
-v – Use this option to attach the /mongodata host volume to the /data/db container volume.
-d – Starts the container as a background process.
--name – Name of the container.

5. By the following command you can see the created docker in your PC.
sudo docker ps

6. Always check the Docker log to see the chain of events after making changes:
sudo docker logs mongodb

7. The container is currently running in detached mode. Connect to the container using the interactive terminal instead:
sudo docker exec -it mongodb bash

8. In the interactive terminal, now able to connect to the mongodb container with the mongo client:
mongo
Note: Now we can execute all mongo commands here.

Thank you for reading this article.