UK based website and application support - contact form.

Blog.

Setting Up MongoDB with Replica Set

Cover Image for Setting Up MongoDB with Replica Set

What is Replica Set?

In MongoDB, a replica set is a group of MongoDB servers that maintain the same dataset, providing high availability and redundancy. Each replica set consists of multiple servers, typically one primary and several secondary nodes.

The primary node handles all write operations, and changes made to the data are then replicated to the secondary nodes. Secondary nodes act as backups of the primary node, replicating its data in real-time to ensure consistency. In the event of a primary node failure, replica sets enable one of the secondary nodes to automatically become the new primary through an election process, ensuring minimal downtime. Replica sets are fundamental to MongoDB’s data reliability, allowing for automatic failover, redundancy, and backup capabilities.

Setting up local Mongo Database

I will use Docker Compose to set up MongoDB as it provides an easy way to manage MongoDB instances within Docker containers.

Docker Compose over standalone Docker commands offers several advantages, especially for managing multi-container applications and environments where configuration consistency and automation are essential.

Docker Compose allows you to define and orchestrate multiple services (e.g., a web server, database, cache) in a single YAML file, rather than starting each service separately with individual Docker commands.

The docker-compose.yml file centralizes configuration for services, networks, and volumes, making setup, maintenance, and changes more straightforward. You can also version control this configuration, ensuring team members work with the same environment.

With Docker Compose, running docker-compose up replicates the same multi-container environment every time, which is helpful in local development, testing, and even in deployment pipelines.

Compose automatically configures networking between containers defined in the same docker-compose.yml, meaning containers can easily communicate by service name without additional network setup.

Docker Compose simplifies working with multi-service applications, automates container configuration, and ensures consistency across different environments, making it a valuable tool for both development and production setups.

Create docker-compose.yml file

Start by creating a docker-compose.yml file to define the MongoDB service and any related configurations. Specify the MongoDB image, version, ports, and any optional environment variables.

Map MongoDB’s default port (27017) so it can be accessed outside the container if needed. Using Docker volumes helps persist MongoDB data on your host system, so the data isn’t lost when the container is stopped.


services:
  mongo1:
    image: mongo:6.0
    command: mongod --replSet myReplicaSet --bind_ip 127.0.0.1,mongo1
    ports:
      - "27017:27017"
    volumes:
      - ./data/mongo1:/data/db
    networks:
      - mongo-network

  mongo2:
    image: mongo:6.0
    command: mongod --replSet myReplicaSet --bind_ip 127.0.0.1,mongo2
    ports:
      - "27018:27017"
    volumes:
      - ./data/mongo2:/data/db
    networks:
      - mongo-network

  mongo3:
    image: mongo:6.0
    command: mongod --replSet myReplicaSet --bind_ip 127.0.0.1,mongo3
    ports:
      - "27019:27017"
    volumes:
      - ./data/mongo3:/data/db
    networks:
      - mongo-network

networks:
  mongo-network:
    driver: bridge

Create a directory named data in the same location as your docker-compose.yml file. This will be used to persist the MongoDB data.

Start the containers using Docker Compose:

docker-compose up -d

Initialize Replica Set

Initialize the replica set by connecting to one of the MongoDB instances (e.g., mongo1) by running the following command:

docker-compose exec mongo1 mongosh

Once you're in the MongoDB shell, run:

rs.initiate({
  _id: "myReplicaSet",
  members: [
    { _id: 0, host: "mongo1:27017" },
    { _id: 1, host: "mongo2:27017" },
    { _id: 2, host: "mongo3:27017" }
  ]
})

Check the status of the replica set:

rs.status()

This configuration sets up a MongoDB replica set with three nodes. Each node runs in a separate container and is connected through a Docker network. The data is persisted using Docker volumes.

Connect to local MongoDB instance from Node.js

Once we have our MongoDB replica set up and running, we can connect to it from our Node.js application. You can test connection using apps likeMongoDB Compass or directly via Terminal

Connection String: mongodb://mongo1:27017,mongo2:27018,mongo3:27019/?replicaSet=myReplicaSet

Example connection using Mongoose:

const connection = await mongoose
    .createConnection(url, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      dbName: dbName,
    })
    .asPromise();

Conclusion

A replica set in MongoDB provides key advantages in terms of availability, data redundancy, and scalability.

If the primary node in a replica set fails, one of the secondary nodes can be automatically elected as the new primary, ensuring minimal downtime and uninterrupted service without manual intervention.

Replica sets maintain copies of your data across multiple servers, providing built-in redundancy. This protects against data loss, as data exists in multiple locations, making it highly resilient to hardware or system failures.

By enabling read operations on secondary nodes, replica sets allow you to distribute read traffic, which can improve performance, especially under heavy load. This is useful for read-heavy applications and improves scalability.

Replica sets facilitate disaster recovery by keeping consistent copies of the data across multiple nodes. If one server experiences a catastrophic failure, other members in the set retain a backup copy of the data.

Having multiple nodes allows you to perform backups on secondary nodes without affecting the performance or availability of the primary node, minimizing impact on production workloads.

← Back to homepage

Looking for website and application support in the Midlands? I specialize in providing comprehensive website maintenance and support services.
Whether you need hosting solutions, web application development, security updates, or assistance with in-house or remote teams, I can help.

My expertise covers React, Next.js, JavaScript, TypeScript, Web Components, Lit, Stencil.js, Node.js, RESTful APIs, Docker, Kubernetes, and Amazon Web Services.

Get in touch!