Setup MongoDB Replica Set with 2 Nodes

Posted by

What you must know about Replica Set in MongoDB?

  • Replica set in MongoDB is a group of MongoDB servers that maintain the same data set
  • Provides fault tolerance as copies of database reside on multiple servers
  • To secure communication between MongoDB servers in replica set, configure Keyfiles using openssl. Keyfiles are bare minimum security for testing and development environments, however for production purpose, use x.509 certificates

Step 1: Update /etc/hosts with IP address and Hostname information

# nano /etc/hosts srv1 srv2

Step 2: Create Keyfile

  • Each mongod servers in the replica set uses keyfile as the shared password for authenticating other members in the deployment
  • Only mongod instances with the correct keyfile can join the replica set

1.1. Create KeyFile directory

# mkdir -p /etc/mongodb/KeyFile

-p option creates parent directory if it doesn’t exist

1.2 Create Keyfile

# openssl rand -base64 756 > /etc/mongodb/KeyFile/mongodb-key

1.3 Provide read permission for keyfile (most important)

# chmod 400 /etc/mongodb/KeyFile/mongodb-key

# chown -R mongodb:mongodb /etc/mongodb/KeyFile/mongodb-key

Step 3: Copy keyfile to other mongodb server and set similar read permission

  • All servers must have the same key file and located in the same directory, with identical permissions.

Step 4: Create Admin User on Primary Member only

  • login to mongo shell


  • Connect to admin database

use admin

Create administrator user with root privileges

db.createUser({user: “mongoadmin”, pwd: “set-password”, roles:[{role: “root”, db: “admin”}]})

Step 4: Configure MongoDB ReplicaSet

Use your favorite editor (vi or nano) to update /etc/mongodb.conf in both nodes

In Node 1:

# network interfaces
port: 27017

keyFile: /etc/mongodb/KeyFile/mongodb-key

replSetName: rs0

In Node 2:

# network interfaces
port: 27017

keyFile: /etc/mongodb/KeyFile/mongodb-key

replSetName: rs0

Step 5: Restart MongoDB instance on both nodes

$ sudo systemctl restart mongod

$sudo systemctl status mongod

Step 6: Connect to mongo shell on Primary member

mongo -u mongoadmin -p –authenticationDatabase admin

Step 7: Configure Replica Set

Initiate replica set


This command initiates a replica set with the current host as its only member. This is confirmed by the output, which should resemble the following:

{ “info2” : “no configuration specified. Using a default configuration for the set”, “me” : “”, “ok” : 1 }

Add other member to replica set


Verify configuration of replica set



Other Notes:

If you encounter these problems, then you have missed or misconfigured step 1.3

{“error”:{“code”:30,”codeName”:”InvalidPath”,”errmsg”:”error opening file: /etc/mongodb/KeyFile/mongodb-key: bad file”}}}


{“error”:{“code”:30,”codeName”:”InvalidPath”,”errmsg”:”permissions on /etc/mongodb/KeyFile/mongodb-key are too open”}}}