How to set up a MongoDB cluster using Docker?

To build a MongoDB cluster, you can use Docker to quickly deploy it. The basic steps are as follows:

  1. Install Docker and Docker Compose: set up Docker and Docker Compose on the host machine in order to utilize Docker containers for running MongoDB.
  2. Create a Docker Compose file: Generate a file named docker-compose.yaml to define the configuration of the MongoDB cluster.
version: '3'
services:
  mongo1:
    image: mongo
    restart: always
    ports:
      - 27017:27017
    volumes:
      - ./data/mongo1:/data/db
    environment:
      - "MONGO_INITDB_ROOT_USERNAME=admin"
      - "MONGO_INITDB_ROOT_PASSWORD=password"
      - "MONGO_INITDB_DATABASE=admin"
      - "REPLICA_SET=rs0"
      - "SERVICE_NAME=mongo1"
  mongo2:
    image: mongo
    restart: always
    ports:
      - 27018:27017
    volumes:
      - ./data/mongo2:/data/db
    environment:
      - "MONGO_INITDB_ROOT_USERNAME=admin"
      - "MONGO_INITDB_ROOT_PASSWORD=password"
      - "MONGO_INITDB_DATABASE=admin"
      - "REPLICA_SET=rs0"
      - "SERVICE_NAME=mongo2"
  mongo3:
    image: mongo
    restart: always
    ports:
      - 27019:27017
    volumes:
      - ./data/mongo3:/data/db
    environment:
      - "MONGO_INITDB_ROOT_USERNAME=admin"
      - "MONGO_INITDB_ROOT_PASSWORD=password"
      - "MONGO_INITDB_DATABASE=admin"
      - "REPLICA_SET=rs0"
      - "SERVICE_NAME=mongo3"

This configuration file defines three MongoDB containers named mongo1, mongo2, and mongo3. Each container maps to a data directory on the host machine and is configured with an administrator username, password, and database name.

  1. Start the MongoDB cluster: Run the following command in the terminal to start the MongoDB cluster using Docker Compose.
docker-compose up -d

This command will start the MongoDB container in the background and automatically create a replica set named rs0.

  1. Initialize the replica set: Run the following command in the terminal to connect to one of the nodes in the MongoDB cluster and initialize the replica set.
docker exec -it mongo1 mongo admin --eval "rs.initiate({_id: 'rs0', members: [{_id: 0, host: 'mongo1:27017'}, {_id: 1, host: 'mongo2:27017'}, {_id: 2, host: 'mongo3:27017'}]})"

This command will connect to the mongo1 container and execute MongoDB Shell commands to initialize the replica set.

Congratulations, you have successfully set up a MongoDB cluster. You can now use different MongoDB client tools to connect to the cluster and perform data operations.

bannerAds