inchirags@gmail.com Chirag's MongoDB DBA Tutorial https://www.chirags.in
*****************************************************************************************
* Configure MongoDB Replica Set on Ubuntu 24.04 LTS *
*****************************************************************************************
MongoDB Database server:
server1 IP: 192.168.224.134 (Primary)
server2 IP: 192.168.224.135 (Secondary)
server3 IP: 192.168.224.147 (Secondary)
Part 1:
MongoDB Database - Install and Configure MongoDB Replica Set on Ubuntu 24.04 LTS step by step process
MongoDB only supports the 64-bit versions of these platforms. To determine which Ubuntu release your host is running, run the following command on the host's terminal:
$ cat /etc/lsb-release
Step 1: Install MongoDB Community Edition in Ubuntu
1. Import the Public Key
From a terminal, install gnupg and curl if they are not already available:
$ sudo apt-get install gnupg curl
To import the MongoDB public GPG key, run the following command:
$ curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg \
--dearmor
2. Create the List File
Create the list file /etc/apt/sources.list.d/mongodb-org-8.0.list for your version of Ubuntu.
Create the list file for Ubuntu 24.04 (Noble):
$ echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
3.Reload the Package Database
Issue the following command to reload the local package database:
$ sudo apt-get update
4. Install MongoDB Community Server
You can install either the latest stable version of MongoDB or a specific version of MongoDB.
To install the latest stable version, issue the following
$ sudo apt-get install -y mongodb-org
--or--
To install a specific release, you must specify each component package individually along with the version number, as in the following example:
$ sudo apt-get install -y mongodb-org=8.0.0 mongodb-org-database=8.0.0 mongodb-org-server=8.0.0 mongodb-mongosh mongodb-org-mongos=8.0.0 mongodb-org-tools=8.0.0
---or end here--
Step 2: Run MongoDB Community Edition
1. Start MongoDB.
You can start the mongod process by issuing the following command:
$ sudo systemctl start mongod
If you receive an error similar to the following when starting mongod:
Failed to start mongod.service: Unit mongod.service not found.
Run the following command first:
$ sudo systemctl daemon-reload
Then run the start command above again.
2. Verify that MongoDB has started successfully.
$ sudo systemctl status mongod
You can optionally ensure that MongoDB will start following a system reboot by issuing the following command:
$ sudo systemctl enable mongod
3. Restart MongoDB.
You can restart the mongod process by issuing the following command:
$ sudo systemctl restart mongod
You can follow the state of the process for errors or important messages by watching the output in the /var/log/mongodb/mongod.log file.
$ tail -f /var/log/mongodb/mongod.log
4. Configure MongoDB User Authentication (Optional but Recommended)
Allowing remote access makes your MongoDB instance more vulnerable to unauthorized access. It’s highly recommended to set up user authentication to secure your database.
5. Create an Admin User in Primary node server (server1 : 192.168.224.134):
Start the MongoDB shell:
mongosh
Switch to the admin database:
use admin
Create an admin user with username and password:
db.createUser({
user: "admin",
pwd: "admin@123",
roles: [{ role: "root", db: "admin" }]
});
To confirm that the admin user has been created, you can list all users in the admin database:
db.getUsers()
Output will be look like below:
admin> db.getUsers()
{
users: [
{
_id: 'admin.admin',
userId: UUID('074ad7bd-d543-4057-9055-809fa963ea65'),
user: 'admin',
db: 'admin',
roles: [ { role: 'root', db: 'admin' } ],
mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
}
],
ok: 1
}
Part 2:
Replica Set
When deploying a MongoDB database for mission-critical applications, configuring a replica set is essential for ensuring high availability and redundancy. A replica set typically includes one primary node, which handles all write operations, and at least two secondary nodes that replicate the data from the primary. This setup minimizes downtime by eliminating a single point of failure.
In the event of a primary node failure, the replica set automatically conducts an election to select a new primary, ensuring continuous operation. While applications can read from secondary nodes, write operations are exclusive to the primary. Although the minimum setup involves three nodes, MongoDB allows for up to 50 members in a replica set, providing scalability and enhanced reliability for your database infrastructure.
1. Configure the Hosts File
MongoDB suggests using DNS hostnames rather than IP addresses for the members of the replica set. Be sure to follow these steps on every server involved.
SSH to the server as a non-root user.
Edit the hosts file.
$ sudo nano /etc/hosts
Locate the line below.
127.0.0.1 localhost
Enter the IP addresses and hostnames as shown under that line.
127.0.0.1 localhost
192.168.224.134 server1
192.168.224.135 server2
192.168.224.147 server3
Save and close the file.
2. Set Up the Replication Key
All servers in the replica set share a base64 key. Follow these steps to install the key.
Use the openssl command to generate a new key on one of the servers (i am generating in primary).
Create and Set Up the Keyfile
If you haven't set up a keyfile, do the following on the primary node:
Create the keyfile:
$ openssl rand -base64 756 > /var/lib/mongodb/keyfile
Set the proper permissions on the keyfile:
$ sudo chmod 400 /var/lib/mongodb/keyfile
$ cat /var/lib/mongodb/keyfile
Copy the keyfile to all replica set members (server2, server3):
$ vi /var/lib/mongodb/keyfile
Make sure the keyfile is in the exact same path on all nodes.
Set the correct permissions on the keyfile on all secondary nodes:
$ sudo chmod 400 /var/lib/mongodb/keyfile
Change the owner and group to mongodb in all servers.
$ sudo chown mongodb:mongodb /var/lib/mongodb/keyfile
3. Configure MongoDB
In this section, you'll configure the shared key, network interface, and replica set name. Repeat these sub-sections on each server.
3.1. Configure the Shared Key
Open mongod.conf in an editor for the following steps.
$ sudo nano /etc/mongod.conf
Find the security section.
security:
authorization: enabled
#operationProfiling:
Below the authorization: line, add the keyFile value as shown.
security:
authorization: enabled
keyFile: /var/lib/mongodb/keyfile
#operationProfiling:
3.2. Configure the Network Interface
Find the network interfaces section.
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1
Add the respective server name after the loopback interface (127.0.0.1) to each server. For example:
On server1:
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1, 192.168.224.134
On server2:
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1, 192.168.224.135
On server3:
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1, 192.168.224.147
3.3. Configure the Replica Set Name
Find the replication section.
#replication:
Remove the Pound comment from the replication line. Below that, add replSetName: "rs0" as shown.
replication:
replSetName: "rs0"
Restart MongoDB on the all node.
$ sudo systemctl restart mongod
4. Bootstrap the Replica Set
In this section, you'll add the nodes to the replica set and bootstrap the replication process.
On the primary node, log in to MongoDB.
$ mongosh -u admin -p --authenticationDatabase admin
Enter the password for your admin account and press Enter to proceed.
Run the following command to add the replica set members.
test> rs.initiate(
{
_id: "rs0",
members: [
{ _id: 0, host: "server1" },
{ _id: 1, host: "server2" },
{ _id: 2, host: "server3" }
]
})
with IP address:
rs.initiate(
{
_id: "rs0",
members: [
{ _id: 0, host: "192.168.224.134:27017" },
{ _id: 1, host: "192.168.224.135:27017" },
{ _id: 2, host: "192.168.224.147:27017" }
]
}
)
You should get the following response when the replica set starts. Notice the prompt changes to rs0 [direct: secondary] test>.
{ ok: 1 }
If this succeeds, you should see all the nodes properly joining the replica set, and you can verify with:
rs.status()
rs0 [direct: secondary] test>
Create a sample company_db database.
rs0 [direct: secondary] test> use company_db
You should get the following response and the prompt changes to rs0 [direct: primary] company_db>. This member is now the primary node.
switched to db company_db
rs0 [direct: primary] company_db>
Insert a sample record in a new employees collection in the company_db database.
rs0 [direct: primary] company_db> db.employees.insertOne({
"employee_id" : 1,
"employee_name" : "CHIRAG MAHTO",
"email" : "inchirags@gmail.com",
"mobile" : "8877663143"
})
You should get the output like below.
{
acknowledged: true,
insertedId: ObjectId("671605cede806b61edfe6911")
}
On each secondary node, log in to MongoDB.
$ mongosh -u admin -p --authenticationDatabase admin
Enter the password for your admin account and press Enter to proceed.
You should see the prompt below, showing that the members are secondary nodes.
rs0 [direct: secondary] test>
On each secondary node, switch to the company_db.
rs0 [direct: secondary] test> use company_db
You should get the following output.
switched to db company_db
Run the following command on each secondary node, which allows them to accept read commands.
rs0 [direct: secondary] company_db> db.getMongo().setReadPref('primaryPreferred')
List the document from the employees collection.
rs0 [direct: secondary] company_db> db.employees.find()
You should get the following output on each secondary node, which shows that the replica set replicated the data to each node.
[
{
_id: ObjectId("671605cede806b61edfe6911"),
"employee_id" : 1,
"employee_name" : "CHIRAG MAHTO",
"email" : "inchirags@gmail.com",
"mobile" : "8877663143"
}
]
Try adding a new employee record on any secondary node.
rs0 [direct: secondary] company_db> db.employees.insertOne({
"employee_id" : 2,
"employee_name" : "PURAB KUMAR",
"email" : "purabapna@gmail.com",
"mobile" : "9876543210"
})
The command should fail. Secondary nodes are read-only.
MongoServerError: not primary
If you stop the primary server or it goes offline, the replica set elects one of the secondary nodes to be the new primary node.
$ sudo systemctl stop mongod
Connect to MongoDB and check.
$ mongosh --port 27017 -u "admin" -p "admin@123" --authenticationDatabase "admin"
use company_db
company_db> db.employees.find()
6. Force Re-Election of a Primary (if necessary)
If the replica set does not have a primary, you can force a new election. On one of the nodes, run:
rs.stepDown()
Or, if there are issues with automatic elections, you can manually reconfigure the replica set to ensure that the correct node is elected primary. In the MongoDB shell, connect to the current primary or secondary and check the configuration:
rs.conf()
You can modify the priorities of the members to influence elections. For example, setting a higher priority on a specific member can ensure it becomes the primary:
cfg = rs.conf()
cfg.members[0].priority = 2
rs.reconfig(cfg)
5. Ensure Replica Set is Healthy
You can check the health of your replica set with:
rs.status()
Part 3:
Steps to Configure the Firewall
1. Check if UFW is Enabled
First, check if UFW is enabled on your Ubuntu system:
sudo ufw status
If it's inactive, enable it with:
sudo ufw enable
2. Allow Local Access (Optional)
If you want to allow access to MongoDB only from localhost (for security purposes), you can run the following command:
sudo ufw allow from 127.0.0.1 to any port 27017
3. Allow Access from Specific IP Addresses (More Secure)
If you need to allow access to MongoDB from a specific IP address (such as the IP of your application server or a development machine), use the following command:
sudo ufw allow from <YOUR_IP> to any port 27017
Replace <YOUR_IP> with the IP address of the machine or server you want to allow access from. For example, if your application server's IP is 192.168.224.159, the command would be:
sudo ufw allow from 192.168.224.134 to any port 27017
sudo ufw allow from 192.168.224.135 to any port 27017
sudo ufw allow from 192.168.224.147 to any port 27017
sudo ufw allow from 192.168.0.137 to any port 27017
4. Allow Access from a Specific Subnet (More Flexible)
If your MongoDB instance needs to be accessed from a range of IPs within a specific subnet (for example, 192.168.224.0/24), you can allow the whole subnet:
sudo ufw allow from 192.168.224.0/24 to any port 27017
5. Allow Access from Anywhere (Less Secure)
To allow MongoDB access from any IP address (this is not recommended for production environments due to security concerns), you can run:
sudo ufw allow 27017
This will open the MongoDB port to the public.
6. Reload UFW to Apply Changes
After making the firewall changes, reload UFW to apply the rules:
sudo ufw reload
7. Check UFW Status
Verify that the rules have been applied by running:
sudo ufw status
You should see rules allowing traffic on port 27017.
Part 4:
A. Connect to MongoDB Replica Set from MongoDB Compass
Once the bindIp settings and firewall rules are configured, you should be able to connect to your MongoDB replica set from MongoDB Compass. Use the following steps:
1. Open MongoDB Compass.
2. Select "Connect using a Connection String".
3. Enter the correct connection string:
mongodb://admin:admin%40123@192.168.224.134:27017,192.168.224.135:27017,192.168.224.147:27017/?replicaSet=rs0&authSource=admin
Here:
admin:admin%40123 is the username (admin) and password (admin@123, with @ encoded as %40).
192.168.224.134:27017,192.168.224.135:27017,192.168.224.147:27017 are the IP addresses of the MongoDB replica set members.
rs0 is the replica set name (replace with the actual name if different).
authSource=admin specifies that the authentication database is admin.
Click "Connect".
B. General Command to Access MongoDB Remotely
Use the following command from the remote server to connect to the MongoDB instance:
mongosh --host <IP>:<PORT> -u <USERNAME> -p <PASSWORD> --authenticationDatabase <AUTH_DB>
Alternatively, if you’re using the older mongo client:
mongo --host <IP>:<PORT> -u <USERNAME> -p <PASSWORD> --authenticationDatabase <AUTH_DB>
Example:
Assume:
MongoDB server IP: 192.168.224.134
MongoDB port: 27017
Username: admin
Password: admin@123
Authentication database: admin
You would run:
mongosh --host 192.168.224.134:27017 -u admin -p 'admin@123' --authenticationDatabase admin
Breaking Down the Command:
--host <IP>:<PORT>: Specifies the IP address and port of the MongoDB server (replace <IP> with the actual IP, and <PORT> with the MongoDB port, usually 27017).
-u <USERNAME>: The username to authenticate.
-p <PASSWORD>: The password for the user. Make sure to wrap it in single quotes if it contains special characters, such as @.
--authenticationDatabase <AUTH_DB>: The database where the user is defined, usually admin for admin users.
***********
Testing:
Now you can stop primary MongoDB and refresh the MongoDB Compass.
sudo systemctl stop mongod
For any doubts and query, please write on YouTube video comments section.
Note : Flow the Process shown in video.
Please, Subscribe and like for more videos:
https://youtube.com/@chiragstutorial
Don't forget to, Follow, Like, Share &, Comment
Thanks & Regards,
Chitt Ranjan Mahto "Chirag"
_________________________________________________________________________________________
Note: All scripts used in this demo will be available in our website.
Link will be available in description.