Back to Blog

MongoDB Docker Setup: Complete Implementation Guide

TheDBAdmin Team4 min read
MongoDB Docker Setup: Complete Implementation Guide

Master MongoDB containerization with this comprehensive guide covering Docker setup, Docker Compose configurations, security best practices, and production deployment strategies.

Setting up MongoDB in a containerized environment offers flexibility, scalability, and consistency across different environments. This comprehensive guide will walk you through setting up MongoDB using both Docker and Docker Compose, with production-ready configurations.

Table of Contents

  1. Prerequisites
  2. Basic Docker Setup
  3. Docker Compose Configuration
  4. Security Best Practices
  5. Production Deployment
  6. Advanced Configurations
  7. Troubleshooting

Prerequisites

Before starting, ensure you have:

  • Docker Engine installed (version 20.10 or later)
  • Docker Compose installed (version 2.0 or later)
  • Basic understanding of MongoDB concepts
  • Terminal access with administrative privileges

Basic Docker Setup

1. Simple MongoDB Container

bash
# Pull the official MongoDB image
docker pull mongodb/mongodb-community-server:6.0-ubi8

# Run a basic MongoDB container
docker run --name mongodb \
  -d \
  -p 27017:27017 \
  mongodb/mongodb-community-server:6.0-ubi8

2. Container with Authentication

bash
# Run MongoDB with authentication
docker run --name mongodb-secure \
  -d \
  -p 27017:27017 \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=secretpassword \
  mongodb/mongodb-community-server:6.0-ubi8

3. Persistent Storage

bash
# Create a Docker volume
docker volume create mongodb_data

# Run MongoDB with persistent storage
docker run --name mongodb-persistent \
  -d \
  -p 27017:27017 \
  -v mongodb_data:/data/db \
  mongodb/mongodb-community-server:6.0-ubi8

Docker Compose Configuration

1. Basic Docker Compose Setup

yaml
# docker-compose.yml
version: '3.8'

services:
  mongodb:
    image: mongodb/mongodb-community-server:6.0-ubi8
    container_name: mongodb
    ports:
      - "27017:27017"
    volumes:
      - mongodb_data:/data/db
    environment:
      - MONGO_INITDB_ROOT_USERNAME=admin
      - MONGO_INITDB_ROOT_PASSWORD=secretpassword

volumes:
  mongodb_data:

2. MongoDB with Replica Set

yaml
# docker-compose-replica.yml
version: '3.8'

services:
  mongodb-primary:
    image: mongodb/mongodb-community-server:6.0-ubi8
    container_name: mongodb-primary
    command: ["--replSet", "rs0", "--bind_ip_all"]
    ports:
      - "27017:27017"
    volumes:
      - mongodb_primary:/data/db
    networks:
      - mongodb_network

  mongodb-secondary1:
    image: mongodb/mongodb-community-server:6.0-ubi8
    container_name: mongodb-secondary1
    command: ["--replSet", "rs0", "--bind_ip_all"]
    volumes:
      - mongodb_secondary1:/data/db
    networks:
      - mongodb_network

  mongodb-secondary2:
    image: mongodb/mongodb-community-server:6.0-ubi8
    container_name: mongodb-secondary2
    command: ["--replSet", "rs0", "--bind_ip_all"]
    volumes:
      - mongodb_secondary2:/data/db
    networks:
      - mongodb_network

volumes:
  mongodb_primary:
  mongodb_secondary1:
  mongodb_secondary2:

networks:
  mongodb_network:
    driver: bridge

3. Initialize Replica Set

javascript
// init-replica.js
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "mongodb-primary:27017" },
    { _id: 1, host: "mongodb-secondary1:27017" },
    { _id: 2, host: "mongodb-secondary2:27017" }
  ]
})

Security Best Practices

1. Custom MongoDB Configuration

yaml
# mongod.conf
security:
  authorization: enabled
  javascriptEnabled: false

net:
  bindIp: 0.0.0.0
  port: 27017
  ssl:
    mode: requireSSL
    PEMKeyFile: /etc/ssl/mongodb.pem

storage:
  dbPath: /data/db
  journal:
    enabled: true

systemLog:
  destination: file
  path: /var/log/mongodb/mongod.log
  logAppend: true

2. Secure Docker Compose Configuration

yaml
# docker-compose-secure.yml
version: '3.8'

services:
  mongodb:
    image: mongodb/mongodb-community-server:6.0-ubi8
    container_name: mongodb-secure
    ports:
      - "27017:27017"
    volumes:
      - mongodb_data:/data/db
      - ./mongod.conf:/etc/mongod.conf
      - ./ssl:/etc/ssl
      - ./logs:/var/log/mongodb
    environment:
      - MONGO_INITDB_ROOT_USERNAME_FILE=/run/secrets/mongo_root_username
      - MONGO_INITDB_ROOT_PASSWORD_FILE=/run/secrets/mongo_root_password
    command: ["--config", "/etc/mongod.conf"]
    secrets:
      - mongo_root_username
      - mongo_root_password
    ulimits:
      nproc: 64000
      nofile:
        soft: 64000
        hard: 64000

volumes:
  mongodb_data:

secrets:
  mongo_root_username:
    file: ./secrets/root_username.txt
  mongo_root_password:
    file: ./secrets/root_password.txt

Production Deployment

1. Resource Limits

yaml
# docker-compose-production.yml
services:
  mongodb:
    deploy:
      resources:
        limits:
          cpus: '2'
          memory: 4G
        reservations:
          cpus: '1'
          memory: 2G

2. Monitoring Setup

yaml
# docker-compose-monitoring.yml
services:
  mongodb:
    # ... existing configuration ...
    
  mongodb-exporter:
    image: percona/mongodb_exporter:0.20
    container_name: mongodb-exporter
    command:
      - '--mongodb.uri=mongodb://admin:password@mongodb:27017'
    ports:
      - "9216:9216"
    depends_on:
      - mongodb

Advanced Configurations

1. Sharded Cluster Setup

yaml
# docker-compose-sharded.yml
version: '3.8'

services:
  configserver1:
    image: mongodb/mongodb-community-server:6.0-ubi8
    command: ["--configsvr", "--replSet", "configReplSet"]
    volumes:
      - configserver1:/data/db
    networks:
      - mongodb_network

  shard1-1:
    image: mongodb/mongodb-community-server:6.0-ubi8
    command: ["--shardsvr", "--replSet", "shard1ReplSet"]
    volumes:
      - shard1-1:/data/db
    networks:
      - mongodb_network

  mongos:
    image: mongodb/mongodb-community-server:6.0-ubi8
    command: "mongos --configdb configReplSet/configserver1:27017"
    ports:
      - "27017:27017"
    networks:
      - mongodb_network
    depends_on:
      - configserver1
      - shard1-1

volumes:
  configserver1:
  shard1-1:

networks:
  mongodb_network:
    driver: bridge

2. Backup Configuration

yaml
# docker-compose-backup.yml
services:
  mongodb:
    # ... existing configuration ...

  mongodb-backup:
    image: mongo:6.0
    volumes:
      - ./backups:/backups
    entrypoint: ["/bin/bash", "-c"]
    command:
      - |
        while true; do
          mongodump --uri="mongodb://admin:password@mongodb:27017" --out="/backups/$(date +%Y%m%d)"
          sleep 86400
        done
    depends_on:
      - mongodb

Troubleshooting

Common Issues and Solutions

  1. Container fails to start:
bash
# Check container logs
docker logs mongodb

# Check MongoDB logs
docker exec mongodb cat /var/log/mongodb/mongod.log
  1. Connection issues:
bash
# Test network connectivity
docker exec mongodb mongosh --eval "db.runCommand({ping: 1})"

# Check container networking
docker network inspect mongodb_network
  1. Performance issues:
bash
# Monitor container resources
docker stats mongodb

# Check MongoDB metrics
docker exec mongodb mongosh --eval "db.serverStatus()"

Best Practices Summary

  1. Security:

    • Always enable authentication
    • Use secrets management
    • Implement network isolation
    • Regular security audits
  2. Performance:

    • Set appropriate resource limits
    • Monitor container metrics
    • Use volume mounts for persistence
    • Implement proper indexing
  3. Maintenance:

    • Regular backups
    • Monitor logs
    • Update container images
    • Health checks

Conclusion

Setting up MongoDB with Docker and Docker Compose provides a flexible and scalable database environment. By following this guide's best practices and security recommendations, you can create a robust, production-ready MongoDB deployment.

Remember to:

  • Regularly update MongoDB and Docker images
  • Monitor container and database performance
  • Implement proper backup strategies
  • Follow security best practices

Additional Resources

Written by

TheDBAdmin Team

KEEP LEARNING WITH THEDBADMIN

Turn this guide into a skill you can prove

Keep reading

Featured course · New batch

NextGen DBA + AI Engineer Bootcamp

Instructor-led, lab-first training for production DBAs: PostgreSQL, MongoDB, Docker, Kubernetes and AI.

  • Live labs on real execution plans
  • Backup, PITR & HA in production
  • pgvector, RAG & AI for DBAs

🛒 FROM THE SHOP

PostgreSQL Observability Pipeline with Prometheus, Grafana, and Alloy

PDF · 10 pages

Free

View product