MongoDB
database setup
Docker container
initialization
tutorial

How to create a DB for MongoDB container on start up?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Overview

When deploying applications using Docker containers, initializing databases like MongoDB upon startup is a common requirement. This ensures that the database is ready, configured, and possibly pre-filled with essential data for application operation. This article will guide you through the steps necessary to create a MongoDB database automatically when the MongoDB container starts. We'll delve into using docker-compose, initialization scripts, and other methodologies for setting up the MongoDB database.

Prerequisites

Before you begin, ensure you have the following:

  • Docker installed on your machine.
  • Basic understanding of Docker and containerization.
  • Basic knowledge of MongoDB.

Using Docker Compose

Docker Compose is a tool used for defining and running multi-container Docker applications. With Docker Compose, you can use a YAML file to configure your application's services. Use the following steps to automatically create a MongoDB database on startup:

Step 1: Create a docker-compose.yml File

Create a docker-compose.yml file to define the MongoDB service. Here's an example configuration:

yaml
1version: '3.8'
2
3services:
4  mongodb:
5    image: mongo:5.0
6    container_name: my_mongo
7    environment:
8      MONGO_INITDB_ROOT_USERNAME: root
9      MONGO_INITDB_ROOT_PASSWORD: example
10      MONGO_INITDB_DATABASE: mydatabase
11    ports:
12      - "27017:27017"
13    volumes:
14      - ./mongo-init-scripts:/docker-entrypoint-initdb.d:ro

Step 2: Initialize Scripts

Place any JavaScript or SQL files into the mongo-init-scripts directory. These scripts will run automatically when the container is initialized.

  1. The directory setup:
bash
   mkdir -p mongo-init-scripts
  1. Create a script file:
    Suppose you want to create a users collection with some initial data.
    File: mongo-init-scripts/init.js
javascript
1   db = db.getSiblingDB('mydatabase');
2
3   db.createCollection('users');
4
5   db.users.insertMany([
6     { username: 'alice', email: '[email protected]' },
7     { username: 'bob', email: '[email protected]' }
8   ]);

Step 3: Run Docker Compose

Execute the following command in the terminal to start the compose services:

bash
docker-compose up

Explanation

  • Environment Variables: The MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD, and MONGO_INITDB_DATABASE are used to set up the root user's credentials and the initial database the scripts will target.
  • Volume Mounting: The scripts are mounted to /docker-entrypoint-initdb.d, which the MongoDB Docker image monitors for initialization scripts.

Summary Table

StepDescription
docker-compose.ymlDefines the MongoDB service with initial setup parameters.
Initialization ScriptsJavaScript/SQL files placed in mongo-init-scripts to initialize the database and collections.
Running ServiceExecute docker-compose up to start the container and apply configurations.

Additional Considerations

Authentication and Security

  • Environment Variables: Avoid hardcoding passwords or sensitive information in the compose file. Use a .env file to store environment variables, which can be referenced in the docker-compose.yml file.
  • Network Configuration: Ensure that the MongoDB instance is only accessible within the Docker network or from specified trusted sources.

Scaling and Management

  • Container Naming and Networking: Use meaningful names for containers and networks. Consider network segmentation if deploying a multi-tier application.
  • Data Persistence: Ensure data durability by connecting a persistent volume to the /data/db directory inside the container.

Automated Deployment

For automated deployment scenarios, integrate this setup with CI/CD pipelines to ensure seamless database deployment and setup in different environments including staging, testing, and production.

Conclusion

This guide provides a method for initializing a MongoDB database in a containerized environment using Docker Compose. Through the use of initialization scripts and proper configuration, automating the creation and setting up of databases becomes streamlined, reducing manual setup and enhancing reproducibility across different systems.

By utilizing Docker's capabilities and MongoDB's flexibility, you ensure that your applications have a consistent database environment irrespective of where they are deployed.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.