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 ⚙️

  1. Edit Config Files

    • Modify mongod.conf on each node to set replication options:
      replication:
        replSetName: "myReplicaSet"
      
      Replace <关键词> with your desired replica set name
      Replica_Set_Configuration
  2. Start MongoDB Instances

    • Run mongod --config /path/to/mongod.conf on all nodes
    • Verify startup logs for errors 🛠️
  3. Initialize Replica Set

    • Connect to the primary node via mongo shell:
      rs.initiate()
      
    • Add secondary and arbiter nodes:
      rs.add("<secondary_host>:27017")
      rs.addArbiter("<arbiter_host>:27017")
      
      Use <关键词> as hostnames

3. Verify Replication Status 🧪

  • Check status with:
    rs.status()
    
  • Ensure all nodes are in SECONDARY state ✅
  • Monitor sync progress using:
    db.currentOp()
    
    Replication_Status_Check

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.

Primary_Secondary_Arbiter