Provisioning MongoDB Container using Docker-Compose

What follows are the steps to get MongoDB container up and running, with the emphasis on docker-compose.yml file and configuration options.

1. ".env" - File with environment variables

MONGO_ROOT_USER=mongo
MONGO_ROOT_PASSWORD=mongo
TZ=Asia/Kolkata
PORT=27017

2. "mongod.conf" - MongoDB configuration file

net:
   bindIp: localhost
   port: 27017
#processManagement:
#   fork: true
#storage:
#   dbPath: /var/lib/mongodb
#systemLog:
#   destination: file
#   path: "/var/log/mongodb/mongod.log"
#   logAppend: true
#storage:
#   journal:
#      enabled: true

3. "docker-compose.yml" - File with container configurations

x-restart-policy: &restart-policy
  restart: unless-stopped

x-log-policy: &log-policy
  logging:
    driver: "json-file"
    options:
      max-file: "2"
      max-size: "5m"

services:
  mongo:
    image: mongo:${TAG:-7.0-jammy}
    environment:
      - MONGO_INITDB_ROOT_USERNAME=${MONGO_ROOT_USER:-mongo}
      - MONGO_INITDB_ROOT_PASSWORD=${MONGO_ROOT_PASSWORD:-mongo}
      - TZ=${TZ:-Asia/Kolkata}
    ports:
      - ${PORT:-27017}:27017
    volumes:
      - ./mongod.conf:/etc/mongod.conf
      - mongo-data:/data/db
    command: ["mongod","--config","/etc/mongod.conf"]
    healthcheck:
      test: echo 'db.runCommand({serverStatus:1}).ok' | mongo admin -u $MONGO_INITDB_ROOT_USERNAME -p $MONGO_INITDB_ROOT_PASSWORD --quiet | grep 1
      interval: 10s
      timeout: 10s
      retries: 3
      start_period: 20s
    container_name: mongo
    <<: *restart-policy
    <<: *log-policy

volumes:
  mongo-data:

4. Instantiate the container

docker compose up -d && \
docker logs -f mongo