MongoDB with Docker: Get started in 5 minutes

MongoDB with Docker: Get started in 5 minutes

6 mins read
Oct 31, 2025
Share
editor-page-cover
Content
Why use MongoDB with Docker?
Getting started
Setting up a MongoDB container
Keep the learning going.
Persisting data with volumes and handling permissions
Interacting with a MongoDB container
Using Docker Compose for multi-container development stacks
Enabling authentication, health checks, and resilience
Replication / Replica Sets in Docker
Wrapping up and next steps
Continue learning about MongoDB and Docker

MongoDB is a popular NoSQL database that uses documents for data storage. MongoDB is considered schema-less, which means that it doesn’t require a defined database schema. It’s a great tool if you want to scale and evolve quickly, as it supports rapid iterative development and allows multiple team members to collaborate.

Docker is a tool that you can use to build applications that run on your host operating system. It runs natively on Linux. Docker uses containers and allows you to combine your application with all its dependencies into a single unit. With Docker, it’s easy to create a container and start working with different technologies.

In this tutorial, we’ll create a MongoDB container using Docker.

Let’s get started!


Get hands-on with MongoDB

Learn MongoDB fast with interactive exercises.

The Definitive Guide to MongoDB

Why use MongoDB with Docker?#

MongoDB enables high availability and scalability. It works well in distributed environments like Docker containers. Using MongoDB with Docker allows us to have a portable database that can be run on any server platform without having to worry about its configuration. We can use Docker with a MongoDB container image to make the database deployment process more efficient and straightforward.

Containerizing a database provides consistency across different environments and enables a faster development setup. Docker containers are extremely portable, meaning that you can use containers wherever you want to operate. They run easily on the cloud and work with multiple cloud platforms.

Getting started#

It’s time to create our Mongo container! Before we can begin, let’s make sure we have Docker installed onto our device. Once we have Docker installed, we’re ready to get started.

We’ll begin by downloading the latest MongoDB Docker image from Docker Hub. A Docker image is a file that allows us to execute code in a Docker container. This file holds instructions for creating containers that run on Docker. There are different versions of MongoDB images. Each Mongo image serves a different purpose.

We’ll use the standard Mongo image and use the following command:

sudo docker pull mongo

If we want to download a specific version of MongoDB, we can use the same command and append the version tag. It would look something like this:

sudo docker pull mongo:4.0.4

Tip: Check out the Docker Hub to find which tag will work for you.

Setting up a MongoDB container#

Now that we’ve created our Mongo image, we’re ready to set up our MongoDB container. We’ll use a Docker run command to deploy a MongoDB instance and also give it a container name:

docker run --name tutorial mongo

If we downloaded the 4.0.4 version of Mongo, we’d append the version tag to the end like this:

docker run --name tutorial mongo:4.0.4

Note: tutorial is what we named our MongoDB container.


Keep the learning going.#

Learn MongoDB without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments, making learning quick and efficient.

The Definitive Guide to MongoDB


Persisting data with volumes and handling permissions#

A key issue when using MongoDB with Docker is data persistence. If you don’t mount any volume, all your data lives inside the container and is lost when the container is removed. To prevent that:

docker volume create mongo_data
docker run -d \\
--name mongodb \\
-p 27017:27017 \\
-v mongo_data:/data/db \\
mongo:latest

This -v mongo_data:/data/db ensures MongoDB stores its data in a named Docker volume, surviving container restarts. Alternatively, you can bind-mount a host directory:

-v /host/path/mongo_db:/data/db

However, if you use bind mounts, permissions matter: the MongoDB process inside the container might run under a non-root user and needs write access. Many initialization failures come from incorrect file permissions on the host mount. Ensure ownership is aligned, e.g.:

sudo chown -R 999:999 /host/path/mongo_db
chmod 700 /host/path/mongo_db

(where 999:999 is the default MongoDB UID/GID in official images). This avoids “permission denied” or auth failures.

Interacting with a MongoDB container#

We created our container! We’re going to interact with the database through the bash shell client. We’ll use the docker exec command in the interactive terminal to connect to it:

docker exec -it tutorial bash

The above command will connect to our deployment named tutorial using the interactive terminal. It’ll also start the bash shell. Now, we’re ready to start using MongoDB. We can use the following command to launch the MongoDB shell client:

mongo

Let’s create a new database and name it “educativeblog”. We can do it with the following command:

use educativeblog

We can’t use our database until we add data to it. We’re going to create three documents in a dogs collection that will exist in our educativeblog database.

db.dogs.save({ name: “Spot” })
db.dogs.save({ name: “Lucky” })
db.dogs.save({ name: “Mochi” })

If we want to query for our MongoDB data, we can do something like this:

db.dogs.find({ name: “Spot” })

Using Docker Compose for multi-container development stacks#

When your application and database both run in Docker, it’s cleaner to orchestrate via Docker Compose. Create a docker-compose.yml:

version: '3.8'
services:
  mongo:
    image: mongo:latest
    container_name: mongo
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
    volumes:
      - mongo_data:/data/db
    networks:
      - backend

  app:
    build: .
    depends_on:
      - mongo
    networks:
      - backend

volumes:
  mongo_data:

networks:
  backend:

Run docker-compose up -d to launch both your application and the MongoDB service in a shared network. In your application, refer to the database hostname as mongo (service name), e.g. mongodb://root:example@mongo:27017. Compose simplifies managing environment, networking, scaling, and shared volumes.

Enabling authentication, health checks, and resilience#

By default, MongoDB in Docker runs without authentication, which is unsafe for any real use. You can enable root credentials:

docker run -d \
  --name mongodb \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=strongpassword \
  -v mongo_data:/data/db \
  -p 27017:27017 \
  mongo:latest

In Compose, include environment variables as shown above. After startup, clients must supply credentials. Also, consider adding health checks and restart policies:

healthcheck:
  test: echo 'db.runCommand("ping").ok' | mongo localhost:27017 --quiet
  interval: 30s
  timeout: 10s
  retries: 5

restart: unless-stopped

This setup ensures your container restarts automatically if it fails and Docker can monitor its health.

Replication / Replica Sets in Docker#

For higher availability, you can simulate a MongoDB replica set using multiple Docker containers:

version: '3.8'
services:
  mongo1:
    image: mongo:latest
    command: ["mongod", "--replSet", "rs0"]
    ports:
      - "27017:27017"
    volumes:
      - mongo1_data:/data/db

  mongo2:
    image: mongo:latest
    command: ["mongod", "--replSet", "rs0"]
    ports:
      - "27018:27017"
    volumes:
      - mongo2_data:/data/db

  mongo3:
    image: mongo:latest
    command: ["mongod", "--replSet", "rs0"]
    ports:
      - "27019:27017"
    volumes:
      - mongo3_data:/data/db

After containers launch, connect to one and initiate the set:

docker exec -it mongo1 mongo
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "mongo1:27017" },
    { _id: 1, host: "mongo2:27017" },
    { _id: 2, host: "mongo3:27017" }
  ]
})

This gives you a replicated cluster that can tolerate node failures. Use this setup when moving from dev to more robust staging or testing environments.


Wrapping up and next steps#

Congrats on taking your first steps with MongoDB and Docker! Running containers with Docker is very efficient. Creating a MongoDB container allows us to work with a portable and extensible NoSQL database without worrying about the underlying configuration of the devices we want to run it on. MongoDB is the most popular NoSQL database system, and it can be used for many things. There’s still so much more to learn about MongoDB. Some recommended topics to cover next include:

  • Using MongoDB with Node.js
  • MongoDB server
  • MongoDB API and JSON entities

To get started learning these concepts and more, check out Educative’s course The Definitive Guide to MongoDB. In this interactive course, you’ll get to see for yourself why there’s so much hype around MongoDB. You’ll learn basic Mongo command operations, using MongoDB in C# and .NET Core, and much more. Throughout the way, you’ll use MongoDB to build projects as you learn. By the end, you’ll know all about how to use MongoDB databases.

Happy learning!


Continue learning about MongoDB and Docker#


Written By:
Erin Schaffer