Create a MongoDB Replica Set

Create 3 mongodb servers. Make sure update hosts files on all nodes or on DNS server mongodb01 mongodb02 mongodb03

Generate a key file on mongodb01

openssl rand -base64 741 > keyfile
scp keyfile mongodb02:~/
scp keyfile mongodb03:~/

Do following commands on all servers

sudo mkdir /opt/mongodb
sudo mv ~/keyfile /opt/mongodb
sudo chmod 400 /opt/mongodb/keyfile

Update ownership on Ubuntu/Debian:

sudo chown mongodb:mongodb /opt/mongodb/keyfile

Update ownership on CentOS

sudo chown mongod:mongod /opt/mongodb/keyfile
sudo chcon system_u:object_r:mongod_var_lib_t:s0 /opt/mongodb/keyfile

Create an Administrator User (only on primary node: mongodb01)

use admin
db.createUser({user: "mongo-admin", pwd: "password", roles:[{role: "root", db: "admin"}]})

Configure MongoDB

Edit /etc/mongod.conf on all nodes. You can edit on one node and copy it to other nodes

  port: 27017
#  bindIp:  # Listen to local interface only, comment to listen on all interfaces.

  authorization: enabled
  keyFile: /opt/mongodb/mongo-keyfile

  replSetName: rs0

Restart mongodb on all nodes

sudo systemctl restart mongod

Initiate replication and add members on primary node mongodb01

mongo -u mongo-admin -p --authenticationDatabase admin

If primary node already has data, using following command to prevent secondary node vode. You can change the priority and votes values after database synced.

rs.add( { host: "mongodb02:27017", priority: 0, votes: 0 } )
rs.add( { host: "mongodb03:27017", priority: 0, votes: 0 } )

Check configuration and status



If all slave nodes stuck at STARTUP status, check the host value of primary. You can update as below:

r0:PRIMARY> var cfg = rs.conf()
rs0:PRIMARY> cfg.members[0].host="mongodb01"
rs0:PRIMARY> rs.reconfig(cfg)


Written on March 16, 2018