Setting Up a Three-Node MongoDB Replica Set on CentOS 7

Installl MongoDB

Create a custom YUM repository:

sudo tee /etc/yum.repos.d/mongodb.repo <<EOF
[mongodb-org]
name=MongoDB Repository
baseurl=https://mirrors.aliyun.com/mongodb/yum/redhat/7/mongodb-org/4.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc
EOF

Install the MongoDB package:

sudo yum install -y mongodb-org

Configure the Replica Set

Update MongoDB Configuration

Edit /etc/mongod.conf to enable replictaion:

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

replication:
  oplogSizeMB: 10240
  replSetName: rs0

Restart and enable the service:

sudo systemctl restart mongod
sudo systemctl enable mongod

Initialize the Replica Set

Prepare an initialization script at /var/lib/mongo/init-replica.js:

const replicaConfig = {
  _id: "rs0",
  members: [
    { _id: 0, host: "10.10.101.22:27017" },
    { _id: 1, host: "10.10.101.23:27017" },
    { _id: 2, host: "10.10.101.24:27017" }
  ]
};

rs.initiate(replicaConfig);

Apply the configuration from one of the nodes:

mongo --port 27017 < /var/lib/mongo/init-replica.js

Verify Replica Set Status

Connect to the MongoDB shell and check the replica set status:

mongo

Once connected, run:

rs.status()

Tags: mongodb Replica Set CentOS 7 database High Availability

Posted on Sun, 26 Jul 2026 16:04:57 +0000 by mherr170