Skip to content

MongoDB Replica Set

Murat Ugur Eminoglu edited this page May 17, 2022 · 6 revisions

Attention: We have migrated our documentation to our new platform, Ant Media Resources. Please follow this link for the latest and up-to-date documentation.

In this article, I'm going to guide you about how to set up a MongoDB replica set. Since a copy of the data is kept on all servers in the Replica Set structure, the same data can be read from other servers in case of an error in any server. In short, it has a structure that makes itself failover.

MongoDB

First, we determine the primary server ourselves, if any failure occurs on the primary server, other nodes re-determine the primary server among themselves, and when the failed server starts again, the data is automatically synchronized to the failed server.

Test Environment

  • Ubuntu 20.04
  • MongoDB 5.0

In the MongoDB Replica Set installation, we will use a total of 3 servers, 1 primary and 2 secondaries. You can start the installation by following the steps below.

Installation

Set the hostnames and host files on all nodes as below.

#node1

hostnamectl set-hostname mongodb1

#node2

hostnamectl set-hostname mongodb2

#node3

hostnamectl set-hostname mongodb3

Run the following command on all nodes.

cat <<EOF>> /etc/hosts
192.168.1.231  mongodb1
192.168.1.232 mongodb2
192.168.1.233 mongodb3
EOF

Install the 5.0 version of MongoDB on all nodes.

wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu `lsb_release -cs`/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org

I have added the admin user by selecting the mongodb1 server as primary.

Run the query below by writing mongo in CLI and accessing the MongoDB console.

use admin

db.createUser(
    {
        user: "superadmin",
        pwd: "admin",
        roles: [ "root" ]
    }
)

Edit the mongodb.conf file on all nodes as below.

net:
  port: 27017
  bindIp: 0.0.0.0

security:
  authorization: enabled
  keyFile: "/etc/key"

replication:
  replSetName: antmediarepl

Save the changes and exit.

Create a key with OpenSSL on the primary node as below and copy the same key to all nodes.

openssl rand -base64 756 > /etc/key

After copying the key file to all nodes, run the command below and give them the necessary permissions and ownership.

chown -R mongodb:mongodb /etc/key && chmod 400 /etc/key

Lastly, enable the MongoDB service on all nodes and restart.

systemctl enable mongod
systemctl restart mongod

Now, let’s start the replication process. Login to MongoDB on Primary as below and start the replica set process by using rs.initiate()

mongo -u superadmin -p 
rs.initiate()

Use the rs.add("node:port") parameter to add the other nodes.

rs.add("192.168.1.231:27017")
rs.add("192.168.1.232:27017")

After all the nodes are added, you can see the status of the nodes in detail with the rs.status() command. What you should pay attention to here is that PRIMARY/SECONDARY nodes should be correct and they have the same timestamp.

rs.status() 

antmediarepl:PRIMARY> rs.status()
{
 "set" : "antmediarepl",
 "date" : ISODate("2021-07-25T12:16:49.796Z"),
 "myState" : 1,
 "term" : NumberLong(1),
 "syncSourceHost" : "",
 "syncSourceId" : -1,
 "heartbeatIntervalMillis" : NumberLong(2000),
 "majorityVoteCount" : 2,
 "writeMajorityCount" : 2,
 "votingMembersCount" : 3,
 "writableVotingMembersCount" : 3,
 "optimes" : {
  "lastCommittedOpTime" : {
   "ts" : Timestamp(1627215401, 1),
   "t" : NumberLong(1)
  },
  "lastCommittedWallTime" : ISODate("2021-07-25T12:16:41.403Z"),
  "readConcernMajorityOpTime" : {
   "ts" : Timestamp(1627215401, 1),
   "t" : NumberLong(1)
  },
  "appliedOpTime" : {
   "ts" : Timestamp(1627215401, 1),
   "t" : NumberLong(1)
  },
  "durableOpTime" : {
   "ts" : Timestamp(1627215401, 1),
   "t" : NumberLong(1)
  },
  "lastAppliedWallTime" : ISODate("2021-07-25T12:16:41.403Z"),
  "lastDurableWallTime" : ISODate("2021-07-25T12:16:41.403Z")
 },
 "lastStableRecoveryTimestamp" : Timestamp(1627215381, 1),
 "electionCandidateMetrics" : {
  "lastElectionReason" : "electionTimeout",
  "lastElectionDate" : ISODate("2021-07-25T10:21:21.110Z"),
  "electionTerm" : NumberLong(1),
  "lastCommittedOpTimeAtElection" : {
   "ts" : Timestamp(0, 0),
   "t" : NumberLong(-1)
  },
  "lastSeenOpTimeAtElection" : {
   "ts" : Timestamp(1627208481, 1),
   "t" : NumberLong(-1)
  },
  "numVotesNeeded" : 1,
  "priorityAtElection" : 1,
  "electionTimeoutMillis" : NumberLong(10000),
  "newTermStartDate" : ISODate("2021-07-25T10:21:21.119Z"),
  "wMajorityWriteAvailabilityDate" : ISODate("2021-07-25T10:21:21.127Z")
 },
 "members" : [
  {
   "_id" : 0,
   "name" : "mongodb1:27017",
   "health" : 1,
   "state" : 1,
   "stateStr" : "PRIMARY",
   "uptime" : 7360,
   "optime" : {
    "ts" : Timestamp(1627215401, 1),
    "t" : NumberLong(1)
   },
   "optimeDate" : ISODate("2021-07-25T12:16:41Z"),
   "syncSourceHost" : "",
   "syncSourceId" : -1,
   "infoMessage" : "",
   "electionTime" : Timestamp(1627208481, 2),
   "electionDate" : ISODate("2021-07-25T10:21:21Z"),
   "configVersion" : 5,
   "configTerm" : 1,
   "self" : true,
   "lastHeartbeatMessage" : ""
  },
  {
   "_id" : 1,
   "name" : "192.168.1.232:27017",
   "health" : 1,
   "state" : 2,
   "stateStr" : "SECONDARY",
   "uptime" : 6903,
   "optime" : {
    "ts" : Timestamp(1627215401, 1),
    "t" : NumberLong(1)
   },
   "optimeDurable" : {
    "ts" : Timestamp(1627215401, 1),
    "t" : NumberLong(1)
   },
   "optimeDate" : ISODate("2021-07-25T12:16:41Z"),
   "optimeDurableDate" : ISODate("2021-07-25T12:16:41Z"),
   "lastHeartbeat" : ISODate("2021-07-25T12:16:49.760Z"),
   "lastHeartbeatRecv" : ISODate("2021-07-25T12:16:49.759Z"),
   "pingMs" : NumberLong(0),
   "lastHeartbeatMessage" : "",
   "syncSourceHost" : "mongodb1:27017",
   "syncSourceId" : 0,
   "infoMessage" : "",
   "configVersion" : 5,
   "configTerm" : 1
  },
  {
   "_id" : 2,
   "name" : "192.168.1.233:27017",
   "health" : 1,
   "state" : 2,
   "stateStr" : "SECONDARY",
   "uptime" : 6899,
   "optime" : {
    "ts" : Timestamp(1627215401, 1),
    "t" : NumberLong(1)
   },
   "optimeDurable" : {
    "ts" : Timestamp(1627215401, 1),
    "t" : NumberLong(1)
   },
   "optimeDate" : ISODate("2021-07-25T12:16:41Z"),
   "optimeDurableDate" : ISODate("2021-07-25T12:16:41Z"),
   "lastHeartbeat" : ISODate("2021-07-25T12:16:49.760Z"),
   "lastHeartbeatRecv" : ISODate("2021-07-25T12:16:48.484Z"),
   "pingMs" : NumberLong(0),
   "lastHeartbeatMessage" : "",
   "syncSourceHost" : "mongodb1:27017",
   "syncSourceId" : 0,
   "infoMessage" : "",
   "configVersion" : 5,
   "configTerm" : 1
  }
 ],
 "ok" : 1,
 "$clusterTime" : {
  "clusterTime" : Timestamp(1627215401, 1),
  "signature" : {
   "hash" : BinData(0,"d1Mk1W/Y8DK73Q/GVFNXAxsu5og="),
   "keyId" : NumberLong("6988807209668837380")
  }
 },
 "operationTime" : Timestamp(1627215401, 1)
}

You can login to the replica set as following.

mongo --host "antmediarepl/mongodb1,mongodb2,mongodb3"

User Guide

Reference

Troubleshooting

Draft

Proposals

Clone this wiki locally