Question: Can you create a MongoDB cluster with 2 nodes?


Creating a MongoDB cluster typically involves setting up a replica set for redundancy and high availability. A replica set is a group of mongod instances that maintain the same data set. MongoDB recommends having an odd number of members in a replica set, primarily to ensure elections for primary can occur smoothly. The minimum recommended configuration for production environments is a three-member replica set, which provides both data redundancy and high availability.

However, technically, you can set up a MongoDB cluster with only two nodes by configuring one as the primary node and the other as a secondary node. This setup is not ideal for production environments because it lacks redundancy (if one node goes down, no automatic failover happens unless an arbiter is added), but it might be suitable for development or testing environments.

To configure a minimal replica set with two nodes, follow these steps:

  1. Initialize the Replica Set on Each Node: Start each MongoDB instance (mongod) with the --replSet option specifying the same replica set name for both nodes.

    On the first node:

    mongod --port 27017 --dbpath /data/db1 --replSet rs0

    On the second node:

    mongod --port 27018 --dbpath /data/db2 --replSet rs0
  2. Connect to One Node and Configure the Replica Set: Use the mongo shell to connect to one of the nodes and execute the rs.initiate() method with a configuration document specifying both nodes.

    Connect to the mongo shell on the first node:

    mongo --port 27017

    Then initiate the replica set:

    rs.initiate({ _id: "rs0", members: [ { _id: 0, host: "localhost:27017" }, { _id: 1, host: "localhost:27018" } ] })
  3. Verify the Replica Set Configuration: After initiating, use the rs.status() command in the mongo shell to check the health and status of the replica set.

For redundancy and failover capabilities in a two-node setup, consider adding an arbiter. An arbiter participates in elections but does not hold data, making it a cost-effective way to achieve an odd number of votes without needing additional data-bearing nodes.

Example to add an arbiter:

mongod --port 27019 --dbpath /data/dbArbiter --replSet rs0

And then add it to the replica set:


Using an arbiter ensures that your two-node cluster can still perform automatic failover and election processes effectively, although it still doesn't provide the full redundancy of having multiple data-bearing nodes.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.