MongoDB replication ensures high availability and data redundancy by synchronizing data across multiple nodes. Here's a step-by-step guide to set up a basic replication configuration:
1. Prerequisites 📋
- At least 3 MongoDB instances (Primary, Secondary, Arbiter)
- Ensure all nodes can communicate over port 27017
- Shared storage for replica set members (optional for Arbiter)
2. Configuration Steps ⚙️
Edit Config Files
- Modify
mongod.conf
on each node to setreplication
options:
Replacereplication: replSetName: "myReplicaSet"
<关键词>
with your desired replica set name
- Modify
Start MongoDB Instances
- Run
mongod --config /path/to/mongod.conf
on all nodes - Verify startup logs for errors 🛠️
- Run
Initialize Replica Set
- Connect to the primary node via
mongo
shell:rs.initiate()
- Add secondary and arbiter nodes:
Users.add("<secondary_host>:27017") rs.addArbiter("<arbiter_host>:27017")
<关键词>
as hostnames
- Connect to the primary node via
3. Verify Replication Status 🧪
- Check status with:
rs.status()
- Ensure all nodes are in
SECONDARY
state ✅ - Monitor sync progress using:
db.currentOp()
4. Testing Failover 🔄
- Simulate primary failure:
kill <primary_process_id>
- Observe automatic failover to a secondary node 🚨
- Validate data consistency across all members 🧾
For advanced configurations, check our Replication Best Practices guide.