Setup and install MongoDB clusters on Ubuntu 20.04

Note : For an easy setup you can follow the all steps below except the part ( Initializing the Replica Set ) in one server and then clone the instance and just make changes in hostnames in all the places.

Step 1- Prepare the Server

Disable firewall for MongoDB. run “sudo ufw disable” to disable firewall 

Set Hostnames for each instance

# in instance 1
sudo hostnamectl set-hostname mongo-cluster-01
# in instance 2
sudo hostnamectl set-hostname mongo-cluster-02
# in instance 3
sudo hostnamectl set-hostname mongo-cluster-03

Each Ubuntu server will have its own MongoDB instance with the standard MongoDB port 27017 accessible through the firewall. MongoDB recommends using logical DNS hostnames instead of IP addresses when configuring replica sets in production environments. That is to avoid disruptions in communication within the replica set due to changes in IP address.
You can update the /etc/hosts file to assign hostnames to each server in a test environment. There, you have to add the below-mentioned hostnames as the hosts indicating each node and reboot each server to load the new configuration.

nano /etc/hosts
# Add this to /etc/hosts
192.168.10.10 mongo-cluster-01
192.168.20.10 mongo-cluster-02
192.168.30.10 mongo-cluster-03

Note : Check the connection between each host with hostname by the ping command

Installing MongoDB on Ubuntu 20.04

Perform the following steps as root or user with sudo privileges to install MongoDB on Ubuntu:

  1. Install the dependencies necessary to add a new repository over HTTPS:
sudo apt update
sudo apt install dirmngr gnupg apt-transport-https ca-certificates software-properties-common

2. Import the repository’s GPG key and add the MongoDB repository with:

wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
sudo add-apt-repository 'deb [arch=amd64] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse'

At the time of writing this article, the latest version of MongoDB is version 4.4. To install another version, replace 4.4 with your preferred version.
Once the repository is enabled, install the mongodb-org meta-package by typing:

sudo apt install mongodb-org

The following packages will be installed on your system:

mongodb-org-server – The mongod daemon and corresponding init scripts and configurations.
mongodb-org-mongos – The mongos daemon.
mongodb-org-shell – The mongo shell, an interactive JavaScript interface to MongoDB. It is used to perform administrative tasks through the command line.
mongodb-org-tools – Contains several MongoDB tools for importing and exporting data, statistics, as well as other utilities.

Start the MongoDB daemon and enable it to start on boot by typing:

sudo systemctl enable --now mongod

To verify whether the installation has been completed successfully, connect to the MongoDB database server using the mongo tool, and print the connection status:

mongo --eval 'db.runCommand({ connectionStatus: 1 })'

The output will look something like the below:

MongoDB shell version v4.4.0
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") }
MongoDB server version: 4.4.0
{
  "authInfo" : {
    "authenticatedUsers" : [ ],
    "authenticatedUserRoles" : [ ]
  },
  "ok" : 1
}

A value of 1 for the ok field indicates success. Check that MongoDB is running by checking that the port ‘27017’ is open.

netstat -plntu

And make sure the mongodb service is active.

# check mongodb status
systemctl status mongod

#restart the MongoDB service
systemctl restart mongod

#start the mongodb service
systemctl start mongod

Configure MongoDB Replica Set

Before starting the MongoDB instance, you need to modify the config file in each server to reflect the IP address and indicate the replica set. Let’s make the following modifications in each mongod.conf file.
A Replica Set is a group of mongod processes in MongoDB that maintain the same data and information. The Replica Set provides high availability and fault tolerance for production deployments of the database.
Replication in mongodb is composed of several MongoDB server instances running mongod process, only one instance runs as ‘PRIMARY’, all other instances are ‘SECONDARY’. Data is written only on the ‘PRIMARY’ instance, the data sets are then replicated to all ‘SECONDARY’ instances.
In this step, we will prepare all server nodes to implement the replica sets in MongoDB.
Create a key file for the inter-cluster authentication

mkdir /opt/mongo/
openssl rand -base64 741 > /opt/mongo/mongodb.key
chmod 600 /opt/mongo/mongodb.key
chown mongod:mongod /opt/mongo/mongodb.key

Then copy this key file on all the cluster members.
Edit and add the below in MongoDB configuration file /etc/mongod.conf in each cluster with nano/vim.
mongo-cluster-01, mongo-cluster-02, mongo-cluster-03

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0

security:
  authorization: enabled
  keyFile: /opt/mongo/mongodb.key

#operationProfiling:
replication:
  replSetName: "mongo-replicaset-prod"

Initializing the Replica Set

You can initialize a replica set using the rs.initiate() method. This method is only required to be executed on a single MongoDB instance in the replica set. Within the initiate method, you can specify the replica set name and member. These details must match with the configurations you made in each config file in the previous step.
In this step, we will create the replica set. We will use the ‘ mongo-cluster-01‘ server as ‘PRIMARY’ node, and ‘ mongo-cluster-02‘ and ‘ mongo-cluster-03‘ as ‘SECONDARY’ nodes.
Login to the mongo3 server and start the mongo shell.

root@mongo-cluster-01:~$ mongo

Initiate the replica set from the mongo1 server with the query below.

rs.initiate( {
   _id : "mongo-replicaset-prod",
   members: [
      { _id: 0, host: "mongo-cluster-01:27017" },
      { _id: 1, host: "mongo-cluster-02:27017" },
      { _id: 2, host: "mongo-cluster-03:27017" }
   ]
})

You will see the results output and make sure there is no error.
Also make sure ‘ok‘ value is 1.
Output:

{
    "ok" : 1,
    "$clusterTime" : {
        "clusterTime" : Timestamp(162344224, 1),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    },
    "operationTime" : Timestamp(162344224, 1)
}

If the replica set was initiated as expected, you’ll notice that the MongoDB client’s prompt will change from just a greater-than sign (>) to the rs0: SECONDRY>

MongoDB comes installed with a few built-in methods which you can use to manage and retrieve information about your replica set. Of these, the rs.help() method can be particularly helpful as it returns a list of these replica set methods and descriptions of what they do:

rs.help()

Output :

    rs.status()                                { replSetGetStatus : 1 } checks repl set status
    rs.initiate()                              { replSetInitiate : null } initiates set with default settings
    rs.initiate(cfg)                           { replSetInitiate : cfg } initiates set with configuration cfg
    rs.conf()                                  get the current configuration object from local.system.replset
    rs.reconfig(cfg)                           updates the configuration of a running replica set with cfg (disconnects)
    rs.add(hostportstr)                        add a new member to the set with default attributes (disconnects)
    rs.add(membercfgobj)                       add a new member to the set with extra attributes (disconnects)
    rs.addArb(hostportstr)                     add a new member which is arbiterOnly:true (disconnects)
    rs.stepDown([stepdownSecs, catchUpSecs])   step down as primary (disconnects)
    rs.syncFrom(hostportstr)                   make a secondary sync from the given member
    rs.freeze(secs)                            make a node ineligible to become primary for the time specified
    rs.remove(hostportstr)                     remove a host from the replica set (disconnects)
    rs.secondaryOk()                               allow queries on secondary nodes

    rs.printReplicationInfo()                  check oplog size and time range
    rs.printSecondaryReplicationInfo()             check replica set members and replication lag
    db.isMaster()                              check who is primary
    db.hello()                              check who is primary

    reconfiguration helpers disconnect from the database so the shell will display
    an error, even if the command succeeds.

Next, check the replica sets status with the rs query below.

rs.status()

# or you can also use
rs.isMaster()

Creating SuperUser in MongoDB.

For Mongo Version 2.

db.createUser(
{
    user: "mongoadmin",
    pwd: "$7R0ngP@@sw0Rd",
    roles: [
              { role: "userAdminAnyDatabase", db: "admin" },
              { role: "readWriteAnyDatabase", db: "admin" },
              { role: "dbAdminAnyDatabase", db: "admin" },
              { role: "clusterAdmin", db: "admin" }
           ]
})

For Mongo Version 3 and above.

db.createUser(
   {
       user: "mongoadmin", 
       pwd: "$7R0ngP@@sw0Rd", 
       roles:["root"]
   })

Test the Replication
Test the data set replication from the ‘PRIMARY’ instance ‘mongodb01-movein-ru’ to ‘SECONDARY’ nodes ‘mongodb02-movein-ru’ and ‘mongodb03-movein-ru’.
In this step, we will try to write or create a new database on the ‘PRIMARY’ node ‘mongodb01-movein-ru’, then check if the replication is working by checking the database on ‘SECONDARY’ nodes ‘mongodb03-movein-ru’ and ‘mongodb02-movein-ru’.
Login to the ‘mongodb01-movein-ru’ server and open the mongo shell using command mongo.
Now create a new database ‘lemp’ and new ‘stack’ collection for the database.

use lemp
db.stack.save(
{
    "desc": "LEMP Stack",
    "apps":  ["Linux", "Nginx", "MySQL", "PHP"],
})

Next, go to the ‘SECONDARY’ node ‘mongo2’ and open the mongo shell. Enable reading from the ‘SECONDARY’ node with the query ‘rs.slaveOk()’, and then check if the ‘lemp’ database exists on the ‘SECONDARY’ nodes.

mongo
#for mongo version 2
rs.slaveOk()

# for mongo version 3 and above
rs.secondaryOk()

show dbs

use lemp

show collections

db.stack.find()

Note : use the below command if you want to access primary node directly.

mongo -u mongoadmin -p --host="mongo-replicaset-prod/192.168.10.10,192.168.20.10,192.168.30.10" --port=27017 --authenticationDatabase "admin"

All Done!!!

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments