Docker and Compose

Running MongoDB with Docker and Compose

A container gives every project its own server version and data, removable in one command. MongoDB 1,815 Inc. publishes mongodb/mongodb-community-server on Docker Hub 514 ; the older Docker 514 Official mongo image is community maintained and lags behind. Tags name version and base image: 8.3.11-ubi8-slim pins, 8.3-ubi8 floats.

A throwaway MongoDB container with a named volumeShell
docker run -d --name mern-mongo -p 28017:27017 -v mern-mongo-data:/data/db \
  -e MONGODB_INITDB_ROOT_USERNAME=root -e MONGODB_INITDB_ROOT_PASSWORD=dev-pass \
  mongodb/mongodb-community-server:8.3-ubi8
docker exec -it mern-mongo mongosh -u root -p dev-pass

The MONGODB_INITDB_* variables create a root user on first start and only on first start: once the volume holds an initialized data directory, changing them does nothing. Without the named volume, writes live in the container's writable layer and vanish with docker rm. Compose suits a MERN project better, bringing the API and database up together over a private network.

compose.yaml for an Express API and MongoDBYAML
services:
  mongo:
    image: mongodb/mongodb-community-server:8.3-ubi8
    volumes: [mern-mongo-data:/data/db]
    healthcheck:
      test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping')"]
      interval: 10s
  api:
    build: .
    environment: { MONGODB_URI: "mongodb://mongo:27017/bookshelf" }
    depends_on: { mongo: { condition: service_healthy } }
volumes: { mern-mongo-data: }

The service name mongo is the hostname: Compose runs a DNS resolver on the project network, so nothing needs publishing. The health check matters, because depends_on alone waits for the container to start, not for WiredTiger to finish recovery — the window in which a first connection fails.