MongoDB is a NoSQL database that is used in many web applications nowadays to store the data in the form of objects. Where on the other side docker is also getting so popular to launch the server fast and with using less space to launch it. So docker has created the MongoDB image to launch its container. If you launch the MongoDB image in docker then it will listen on MongoDB port 27017. One can use this combination in this way if you are deploying any web application on the server launch on docker in the backend if you want to store any data then you can use MongoDB as a database. This complete process is faster than any other technology used to deploy the application.
In this article, we will see how to launch the MongoDB image in docker and how to connect two MongoDB containers in which one will act as a client and others will act as a server.
Setting up a MongoDB in Docker
Follow the below steps to set up a MongoDB Container in Docker:
Step 1: To launch any container in docker first you want the image of that particular container so the first step is to log in to your docker hub and search for MongoDB and click on the official image option.
Step 2: When you click on the link you will see the pull command copy that command.
Step 3: Go to your docker host OS and paste that command there it will pull the latest version of MongoDB image into your docker host.
Step 4: After downloading the image now it’s time to launch the container. The command is
sudo docker run -it -d mongo
Description of command:
-it: This option is used to run the container in iterative mode.
-d: This option is used to run containers as a daemon process.
Now run the docker ps command to see the details of the docker container.
Notice the name of the container which is different for everyone here it is priceless_dijkstra and the port number which is 27017/tcp in this case.
Step 5: Now launch another container that will act as a client and connect to the MongoDB database.
sudo docker run -it -link=priceless_dijkstra:mongo mongo /bin/bash
Description of command:
In this command, we are linking the pre-existing container with the new mongo container which we are launching my mentioning the mongo in the command.
Now we are inside the new container.
Step 6: Use the env command to see the details of the new container.
Step 7: Now we are going to connect the MongoDB server container to the client container.
The IP and the port number you will get by using the env command and mongo command is used to connect to the mongo database. After running this command you will connect to the database then you can run any MongoDB command.
Share your thoughts in the comments
Please Login to comment...