How to Install MongoDB with Docker and Docker Compose?

How to Install MongoDB with Docker and Docker Compose?

MongoDB is a leading NoSQL database known for its performance, scalability, and flexibility. It uses a document-oriented data model, storing data in JSON-like documents with dynamic schemas.

This design enables easy data integration, fast query execution, and efficient storage of complex data structures.

Features

One of MongoDB's key features is its speed. It handles large volumes of data and high-throughput operations, making it ideal for real-time analytics, fast data retrieval, and rapid updates. MongoDB uses in-memory storage, efficient indexing, and horizontal scaling via sharding, ensuring seamless application scalability as data volumes grow.

MongoDB's document model offers a flexible way to work with complex or evolving data structures. Documents can contain nested arrays and objects, representing hierarchical relationships within a single record, eliminating the need for complex joins and speeding up read and write operations.

MongoDB also features a powerful query language supporting ad-hoc queries, indexing, and real-time aggregation. This allows easy extraction of insights from large datasets, complex analytics, and building sophisticated data-driven applications.

Security features include authentication, authorization, and encryption, ensuring data remains secure and compliant with industry standards.

Use-cases

Use-Cases of MongoDB include e-commerce, finance, and healthcare. In e-commerce, it manages product catalogs, customer data, and transactions for high-traffic online stores.

In finance, it powers trading platforms, risk management systems, and fraud detection algorithms with real-time data processing.

Healthcare applications use MongoDB for patient records, medical research, and health monitoring systems, handling unstructured data and large datasets efficiently.

  • Instagram: Manages user data, photos, comments, and interactions.
  • Spotify: Stores metadata about songs, playlists, and user preferences for quick access.
  • Uber: Handles dynamic pricing, driver and rider data, and trip information.
  • Reddit: Manages content, user interactions, and high-traffic data operations.

Meteor.js

Meteor.js is an open-source platform built on Node.js, simplifying web and mobile app development. It integrates seamlessly with MongoDB, providing a real-time data layer for highly responsive applications.

It supports rapid prototyping and production deployment with its isomorphic JavaScript framework, enabling the same codebase to run on both client and server. MongoDB and Meteor.js integration ensures automatic data propagation between client and server for a seamless user experience.


Installing MongoDB with Docker and Docker Compose

Prerequisites

  • Docker installed
  • Docker Compose installed

Step 1: Create Project Directory

Create a directory for your MongoDB project to keep your files organized.

mkdir mongodb-docker
cd mongodb-docker

Step 2: Create docker-compose.yml

Create a docker-compose.yml file to define the MongoDB service. This file specifies the Docker image to use, container settings, environment variables, exposed ports, and data volumes.

version: '3.8'

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

volumes:
  mongo_data:
  • version: '3.8': Specifies the version of the Docker Compose file format.
  • services: Defines the services to be run.
  • mongo: Defines the MongoDB service.
    • image: mongo:latest: Uses the latest MongoDB Docker image.
    • container_name: mongodb_container: Names the container mongodb_container.
    • environment: Sets environment variables for the MongoDB container.
      • MONGO_INITDB_ROOT_USERNAME: Username for the MongoDB root user.
      • MONGO_INITDB_ROOT_PASSWORD: Password for the MongoDB root user.
    • ports: Maps the container port 27017 to the host port 27017.
    • volumes: Defines a named volume mongo_data to persist MongoDB data.

Step 3: Start MongoDB Service

Start the MongoDB service in detached mode (running in the background).

docker-compose up -d

Step 4: Verify Installation

Check if the MongoDB container is running by listing all running containers.

docker ps

You should see an entry for mongodb_container.

Step 5: Connect to MongoDB

Connect to the MongoDB database using the MongoDB shell.

docker exec -it mongodb_container mongo --username root --password example

This command connects you to the MongoDB shell inside the running container.

Step 6: Manage MongoDB Service

To stop the MongoDB service, run:

docker-compose down

This stops and removes the container but preserves the data in the mongo_data volume.

To start the service again, use:

docker-compose up -d

Step 7: Customize Configuration

Create an initialization script to set up additional users or databases when MongoDB starts.

Create mongo-init.js:

db.createUser(
  {
    user: "myuser",
    pwd: "mypassword",
    roles: [
      {
        role: "readWrite",
        db: "mydatabase"
      }
    ]
  }
);

This script creates a new user with read/write access to mydatabase.

Modify docker-compose.yml to include the initialization script:

version: '3.8'

services:
  mongo:
    image: mongo:latest
    container_name: mongodb_container
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
    ports:
      - "27017:27017"
    volumes:
      - mongo_data:/data/db
      - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro

volumes:
  mongo_data:
  • ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro: Mounts the mongo-init.js script into the container, ensuring it runs on startup.

You've successfully installed MongoDB using Docker and Docker Compose. This setup is highly configurable and can be adapted to suit various development and testing needs. For more advanced configurations, refer to the official Docker and MongoDB documentation.







Read more




Open-source Apps

9,500+

Medical Apps

500+

Lists

450+

Dev. Resources

900+

/