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.
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
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
-d option is used to run the container in the detached mode, meaning the container will run in the background and won't block your terminal.
--name options allow you to provide a name for your MongoDB container. I have used mongodb here but you can use anything you really want.
-p option 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
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.
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.
To stop a MongoDB Docker container, you can use the following command:
docker stop mongodb
To Start MongoDB again
docker start moongodb
This article was originally published on stacktips.