How to Set Up MongoDB Master‑Slave Replication on CentOS: A Step‑by‑Step Guide
This tutorial walks you through installing MongoDB on three CentOS 7.9 servers, configuring a replica set with a master and two slaves, creating admin and test users, securing communication with key files, and verifying failover by stopping the primary node, all illustrated with commands and screenshots.
MongoDB Introduction
MongoDB is an open‑source document‑oriented NoSQL database that stores data in JSON‑like documents, offering high flexibility, scalability, powerful query language, aggregation framework, and support for various programming languages.
MongoDB Features
Document‑oriented data model with flexible schema.
Distributed architecture with automatic sharding.
High‑performance read/write operations.
Rich query language including aggregation pipelines, geospatial queries, and full‑text search.
Dynamic schema changes and easy extensibility.
Horizontal scalability by adding more servers.
Visual management tools such as MongoDB Compass.
MongoDB Master‑Slave Replication Overview
MongoDB Master‑Slave Replication
Replication synchronizes data from a primary node to multiple secondary nodes, improving reliability and availability. The primary handles write operations, while secondaries handle reads. In case of primary failure, an eligible secondary is automatically elected as the new primary, ensuring high availability.
MongoDB Replica Set
A replica set is a group of mongod instances that maintain the same data set.
It provides redundancy and high availability; a minimum of three members (one primary, one secondary, one arbiter or another secondary) is recommended.
If the primary fails, the remaining members hold an election to select a new primary.
Practice Overview
Practice Environment Planning
hostname IP address OS version MongoDB version Role
master 192.168.3.141 centos 7.9 v5.0.21 Primary
node01 192.168.3.142 centos 7.9 v5.0.21 Secondary
node02 192.168.3.143 centos 7.9 v5.0.21 SecondaryPractice Introduction
1. Prepare three CentOS 7.9 servers. 2. This is a personal test environment; use caution in production. 3. The main goal is to configure MongoDB master‑slave replication.
Install MongoDB
Installation Instructions
All three servers must follow the steps below to install MongoDB.
vim /etc/yum.repos.d/mongodb.repo [mongodb-org]
name=MongoDB Repository
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mongodb/yum/el7/
gpgcheck=0
enabled=1Check YUM repository status
Check the status of YUM repository mirrors.
# yum repolist all | grep enable
base/7/x86_64 CentOS-7 - Base - mirrors.aliyun.com enabled: 10072
extras/7/x86_64 CentOS-7 - Extras - mirrors.aliyun.com enabled: 518
mongodb-org/7 MongoDB Repository enabled: 337
updates/7/x86_64 CentOS-7 - Updates - mirrors.aliyun.com enabled: 5176Install MongoDB
Install MongoDB directly using yum.
yum install -y mongodb-org-server mongodb-orgModify bound IP
Change the bindIp in /etc/mongod.conf to 0.0.0.0.
vim /etc/mongod.confStart MongoDB service
Start and enable MongoDB service.
systemctl start mongod.service && systemctl enable mongod.serviceCheck MongoDB service status
Verify that the MongoDB service is running.
# systemctl status mongod
● mongod.service - MongoDB Database Server
Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2023-09-13 16:38:48 CST; 44s ago
Docs: https://docs.mongodb.org/manual
Main PID: 1472 (mongod)
CGroup: /system.slice/mongod.service
└─1472 /usr/bin/mongod -f /etc/mongod.confCheck MongoDB version
Display the installed MongoDB version.
# mongod --version
db version v5.0.21
Build Info: {
"version": "5.0.21",
"gitVersion": "4fad44a858d8ee2d642566fc8872ef410f6534e4",
"openSSLVersion": "OpenSSL 1.0.1e-fips 11 Feb 2013",
"modules": [],
"allocator": "tcmalloc",
"environment": {
"distmod": "rhel70",
"distarch": "x86_64",
"target_arch": "x86_64"
}
}Master Node Configuration
Enter MongoDB shell
Open the MongoDB shell locally.
mongoCreate admin user
Create an administrator account named admin .
db.createUser({
user: "admin",
pwd: "admin",
roles: [{role: "userAdminAnyDatabase", db: "admin"}]
})Create test user
Authenticate with the admin account and create a test user.
use admin;
db.auth("admin","admin")Create a user huawei with the root role.
db.createUser({
user: "huawei",
pwd: "huawei",
roles: ["root"]
})Access test database
Connect to MongoDB using the admin credentials.
mongo -uadmin -padmin --authenticationDatabase adminCreate key file on master
Generate a key file for internal authentication.
mkdir -p /data/mongodb/
openssl rand -base64 666 > /data/mongodb/mongodb.keyCreate the same directory on the two secondary nodes.
mkdir -p /data/mongodb/Copy key file
Transfer the key file to both secondary nodes.
scp /data/mongodb/mongodb.key [email protected]:/data/mongodb/
scp /data/mongodb/mongodb.key [email protected]:/data/mongodb/All Nodes Configuration
Configuration instructions
Execute the following commands on all three nodes.
Directory and file permissions
Set ownership and permissions for the data directory and key file.
chown mongod:mongod -R /data/mongodb/
chmod 600 /data/mongodb/mongodb.keyEdit /etc/mongod.conf
Update the configuration file on each node.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /var/run/mongodb/mongod.pid
timeZoneInfo: /usr/share/zoneinfo
net:
port: 27017
bindIp: 0.0.0.0
security:
authorization: enabled
keyFile: /data/mongodb/mongodb.key
clusterAuthMode: keyFile
replication:
replSetName: rs0
oplogSizeMB: 5000Restart MongoDB service
Restart the MongoDB service on all nodes.
systemctl restart mongodConfigure MongoDB Replication
User authentication
Connect to the primary node.
mongoAuthenticate with the huawei account.
use admin;
db.auth("huawei","huawei")Configure replica set
Initialize the replica set with one primary and two secondaries.
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "192.168.3.141:27017" },
{ _id: 1, host: "192.168.3.142:27017" },
{ _id: 2, host: "192.168.3.143:27017" }
]
})Check replica set configuration
Authenticate again and view the replica set configuration.
use admin;
db.auth("huawei","huawei")
rs.config()Check replica set status
Display the current status of the replica set.
rs.status()Determine primary node
Identify which host is the primary.
rs.isMaster()Test MongoDB Failover
Stop primary MongoDB service
Stop the MongoDB service on the primary node.
systemctl stop mongod.serviceCheck slave status
Log into a secondary node and verify it has become the new primary.
mongoSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
