How to run MongoDB container

Rahul Kumar
1 min readSep 28, 2024
Photo by Rubaitul Azad on Unsplash

Here’s a simple Docker Compose file to run a MongoDB container:

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

Explanation:

  • version: Specifies the Docker Compose file version.
  • services: Defines the services to be run. Here, we have one service, mongo.
  • image: The Docker image for MongoDB.
  • container_name: The name of the MongoDB container.
  • ports: Maps port 27017 of the container to port 27017 on your host machine.
  • environment: Sets environment variables for the MongoDB root username and password. You can change these values as needed.
  • volumes: Mounts a named volume (mongo_data) to persist MongoDB data even if the container is removed.

Running the Container

To start the MongoDB container using this Docker Compose file:

  1. Save the above YAML configuration in a file named docker-compose.yml.
  2. Open a terminal and navigate to the directory where the file is saved.
  3. Run the following command:
docker-compose up -d

This will start the MongoDB container in detached mode. You can then connect to MongoDB at localhost:27017 with the credentials specified in the environment variables.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Rahul Kumar
Rahul Kumar

Written by Rahul Kumar

Yup! I code this is my superpower.

No responses yet

Write a response