Files
compose-anything/src/mongodb-replicaset
2025-09-24 22:24:11 +08:00
..
2025-09-24 22:24:11 +08:00
2025-09-24 14:16:10 +08:00
2025-09-24 14:16:10 +08:00

MongoDB Replica Set

English | 中文

This service sets up a MongoDB replica set with three members.

Prerequisites

  1. Generate a key file for the replica set:

    openssl rand -base64 756 > ./secrets/rs0.key
    

Initialization

  1. Start the services:

    docker compose up -d
    
  2. Connect to the primary node:

    docker exec -it mongodb-replicaset-mongo1-1 mongosh
    
  3. Initialize the replica set. Remember to replace the host IP with your actual host IP.

    config = {
      _id: "rs0",
      members: [
        {_id: 0, host: "192.168.31.38:27017"},
        {_id: 1, host: "192.168.31.38:27018"},
        {_id: 2, host: "192.168.31.38:27019"},
      ]
    }
    rs.initiate(config)
    

Services

  • mongo1: The first member of the replica set.
  • mongo2: The second member of the replica set.
  • mongo3: The third member of the replica set.

Configuration

  • MONGO_VERSION: The version of the MongoDB image, default is 8.0.13.
  • MONGO_INITDB_ROOT_USERNAME: The root username for the database, default is root.
  • MONGO_INITDB_ROOT_PASSWORD: The root password for the database, default is password.
  • MONGO_INITDB_DATABASE: The initial database to create, default is admin.
  • MONGO_REPLICA_SET_NAME: The name of the replica set, default is rs0.
  • MONGO_PORT_OVERRIDE_1: The host port for the first member, default is 27017.
  • MONGO_PORT_OVERRIDE_2: The host port for the second member, default is 27018.
  • MONGO_PORT_OVERRIDE_3: The host port for the third member, default is 27019.

Volumes

  • secrets/rs0.key: The key file for authenticating members of the replica set.