Join our Discord Server
Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).

How to run MongoDB with Docker and Docker Compose: A Step-by-Step guide

2 min read

If you’re looking to set up MongoDB for your project, Docker Compose offers a simple and efficient way to get started. This guide will take you through the step-by-step process of creating a docker-compose.yml file, running MongoDB as a container, and even using it with a full-stack application like a to-do list built with Node.js and React.

Here’s a simple docker-compose.yml file to set up a MongoDB container using Docker Compose. This configuration includes options for setting the MongoDB version, persistent data storage, and custom environment variables.

Getting Started

Prerequisite

  • Install Docker Desktop

Writing a Compose file

services:
  mongo:
    image: mongo:8.0 
    container_name: mongodb
    restart: always
    ports:
      - "27017:27017" # Expose MongoDB on the default port
    environment:
      MONGO_INITDB_ROOT_USERNAME: root # Set the admin username
      MONGO_INITDB_ROOT_PASSWORD: password # Set the admin password
    volumes:
      - mongo-data:/data/db # Persist MongoDB data
      - mongo-config:/data/configdb # Persist MongoDB configuration

volumes:
  mongo-data:
    driver: local
  mongo-config:
    driver: local

Explanation of the File:

  • image: mongo:8.0: Specifies the MongoDB image and version to pull from Docker Hub.
  • container_name: mongodb: Sets a specific name for the container.
  • restart: always: Ensures the MongoDB container restarts automatically if it stops.
  • ports: “27017:27017”: Maps the container’s MongoDB port (27017) to the host system.
  • environment: Sets environment variables for initializing the MongoDB root user: MONGO_INITDB_ROOT_USERNAME: The username for the database admin. MONGO_INITDB_ROOT_PASSWORD: The password for the database admin. volumes:
  • Defines two persistent volumesmongo-data: For MongoDB data. mongo-config: For MongoDB configuration files.

How to Use:

Save the file as docker-compose.yml.

Run the following commands:

$ docker compose up -d

Results:

docker compose up -d
[+] Running 8/8
 ✔ mongo Pulled                                                                                        14.5s 
   ✔ 734d6dbbc27c Download complete                                                                     0.6s 
   ✔ e696e3f04726 Download complete                                                                     0.9s 
   ✔ 144e60e5b480 Download complete                                                                     0.5s 
   ✔ 1e4f5be70270 Download complete                                                                     0.9s 
   ✔ 8859f6c60d49 Download complete                                                                     1.0s 
   ✔ 84fdaca1efce Download complete                                                                     1.0s 
   ✔ fab452af0a9c Download complete                                                                     8.1s 
[+] Running 4/4
 ✔ Network mongo_default        Created                                                                 0.0s 
 ✔ Volume "mongo_mongo-data"    Created                                                                 0.0s 
 ✔ Volume "mongo_mongo-config"  Created                                                                 0.0s 
 ✔ Container mongodb            Started                                                                 0.9s

Access MongoDB:

mongosh is the modern, official shell for MongoDB. It provides an interactive interface to connect to MongoDB instances and execute commands. If you’ve worked with the older mongo shell, consider mongosh its next-generation replacement with enhanced features and better compatibility.

You can access the database via Docker Dashboard > Click on container > EXEC and running the following command:

"mongosh "mongodb://root:password@localhost:27017"
Image2

Note: You can modify the MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD variables for better security and adjust the volumes or ports as needed.

Bring down the application Stack

$ docker compose down -v

Using Mongo with React and NodeJS

Let’s make things more exciting by connecting MongoDB to a simple to-do list application using Node.js and React.

Step 1. Clone the repository

$ git clone https://github.com/ajeetraina/todo-list

Step 2. Change directory to using-mongo

$ cd todo-list/using-compose/using-mongo

Step 3. Using Nodejs + MongoDB

Run the following command to start both the backend and frontend:

docker compose up -d --build

Accessing the app

image
image

For Mongo Express:

Username: admin
Password: pass

Interacting with Mongo using Docker Dashboard Container Console

mongosh --username ajeetraina --password ajeetraina123 --authenticationDatabase admin
image

Populating todo-List Items

image
test> show dbs
admin       40.00 KiB
config      12.00 KiB
local       40.00 KiB
node-mongo  40.00 KiB
test> use node-mongo
switched to db node-mongo
node-mongo> show collections
items
node-mongo>
db.items.find()
[
  {
    _id: ObjectId('65b8b820e9f51f3c974aa700'),
    title: 'Watch Netflix',
    description: 'Renew the netflix account',
    date: ISODate('2024-01-30T08:49:36.151Z'),
    __v: 0
  },
  {
    _id: ObjectId('65b8b84be9f51f3c974aa703'),
    title: 'Buy Grocery',
    description: 'Carry purse and buy grocery',
    date: ISODate('2024-01-30T08:50:19.520Z'),
    __v: 0
  }
]

Why This Setup Rocks

  1. Persistence: Your data survives container restarts, thanks to volumes.
  2. Ease of Use: Docker Compose simplifies running multi-container applications.
  3. Scalability: You can easily add services (e.g., Redis, RabbitMQ) as needed.

Conclusion

With this setup, you’ve not only deployed MongoDB using Docker Compose but also integrated it into a full-stack application. Whether you’re a beginner or a seasoned developer, this workflow streamlines your development process and ensures your application is ready for scaling.

Got questions or want to explore more? Drop a comment below, and let’s build something awesome together! 🚀

Have Queries? Join https://launchpass.com/collabnix

Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).
Join our Discord Server
Index