StackTipsStackTips

How to Set Up MongoDB within a Docker Container

A step-by-step tutorial that covers how to set up MongoDB within a Docker container effortlessly and expose the container port on your host machine.

July 20, 2023 · 5 min read · Updated Sep 2025

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 a step-by-step guide to setting up MongoDB within a Docker container:

Install Docker

First, make sure you have Docker installed on your machine. If it is not installed, you can download Docker Desktop from the official Docker website. Visit 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 Docker Hub. To do that, open your terminal and run the following command:

docker pull mongo

Run MongoDB Container

Now, run the following command to start 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

Options:

  • The -d option is used to run the container in detached mode, meaning the container will run in the background and won't block your terminal.

  • The --name option allows you to provide a name for your MongoDB container. I have used mongodb here, but you can use anything you want.

  • The -p option is used to map the container's port to the host machine's port. The port 27017 on the left-hand side of the colon (:) represents the port on the host machine, and the right-hand side is the port of MongoDB. The default MongoDB port is 27017.

  • The default MongoDB username and password can be set using the environment variables MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD. The environment variables are provided with the -e option.

This command will start a Docker container named "mongodb" and map the default MongoDB port 27017 from the container to the same port on your host machine.

Verify Running MongoDB Container

You can check if the container is running by executing the command:

docker ps

It should display a list of running containers, and you should see the "mongodb" container in the list.

Stop MongoDB Container

To stop a MongoDB Docker container, you can use the following command:

docker stop mongodb

To start MongoDB again:

docker start mongodb