Skip to content

Instantly share code, notes, and snippets.

@mdmen
Last active October 4, 2023 16:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdmen/5d153ff4624d8e493705dbd627348f35 to your computer and use it in GitHub Desktop.
Save mdmen/5d153ff4624d8e493705dbd627348f35 to your computer and use it in GitHub Desktop.
Setup MongoDB using Docker Compose as single instance (node) replica set

Don't use in production!!! For development purpose only

  1. Create compose.yml file with the following content:
services:
  mongodb:
    image: mongo
    container_name: mongodb
    volumes:
      - mongodb:/data/db
      - ./replica.key:/data/replica.key
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${DATABASE_USER}
      MONGO_INITDB_ROOT_PASSWORD: ${DATABASE_PASSWORD}
    healthcheck:
      test: test $$(echo "rs.initiate().ok || rs.status().ok" | mongosh -u $${MONGO_INITDB_ROOT_USERNAME} -p $${MONGO_INITDB_ROOT_PASSWORD} --quiet) -eq 1
      interval: 10s
      start_period: 5s
    ports:
      - 27017:27017
    command: "--bind_ip_all --keyFile /data/mongo/replica.key --replSet rs0"

  mongo-express:
    image: mongo-express
    container_name: mongo-express
    depends_on:
        mongodb:
            condition: service_healthy
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: ${DATABASE_USER}
      ME_CONFIG_MONGODB_ADMINPASSWORD: ${DATABASE_PASSWORD}
      ME_CONFIG_MONGODB_URL: mongodb://${DATABASE_USER}:${DATABASE_PASSWORD}@mongodb:27017/?replicaSet=rs0&w=majority&readPreference=primary&directConnection=true&authSource=admin
    restart: unless-stopped

volumes:
  mongodb:
  1. Generate replica key:
openssl rand -base64 756 > replica.key
  1. Create .env file with variables:
DATABASE_USER=
DATABASE_PASSWORD=
  1. Run
docker compose up -d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment