How to Set up MongoDB within a Docker Container
In this tutorial, we'll show you how to set up MongoDB in a Docker container. By containerizing MongoDB, you can quickly deploy and use MongoDB effortlessly for your local development.
Here is the step-by-step guide to setting up MongoDB within a Docker container:
First, make sure you have the Docker installed on your machine. If it is not installed, you can download the Docker Desktop from the official Docker website. Visit the website https://docs.docker.com/engine/install/ and download the package appropriate for your operating system.
Pull MongoDB Image
Now, let us pull the official MongoDB docker image from the Docker Hub. For that, open your terminal and run the following command:
$ docker pull mongo
Run MongoDB Container
Now, run the following command to start a MongoDB in a container,
docker run -d --name mongodb -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=YOUR_USERNAME -e MONGO_INITDB_ROOT_PASSWORD=YOUR_PASSWORD mongo
-doption is used to run the container in the detached mode, meaning the container will run in the background and won't block your terminal.
--nameoptions allow you to provide a name for your MongoDB container. I have use
mongodbhere but you can use anything you really want.
-poption is used to map the container’s port into the host machine port. The port 27017 on the left-hand side of the colon (
:) represents the port of the host machine. And the right-hand side port is the port of MongoDB. The default MongoDB port is 27017 .
The default MongoDB user name and password can be set using the environment variable
MONGO_INITDB_ROOT_PASSWORD. The environment variables are provided with
This command will start a Docker container named "MongoDB" and map the MongoDB default port 27017 from the container to the same port on your host machine.
Verify Running Mongo Container
You can check if the container is running by executing the command:
It should display a list of running containers, and you should see the "mongodb" container in the list.
Stop Mongo Container
To stop a MongoDB Docker container, you can use the following command:
docker stop mongodb
To Start MongoDB again
docker start moongodb
Sharing is caring!
Did you like what Nilanchala Panigrahy 🌱 wrote? Thank them for their work by sharing it on social media.