Dragonfly

Question: How do you set up MongoDB replication on Docker?

Answer

Setting up MongoDB replication on Docker involves creating a MongoDB replica set using multiple Docker containers. A replica set is a group of MongoDB instances that maintain the same data set. Here's a step-by-step guide to set this up:

Step 1: Create a Docker Network

First, create a Docker network for your MongoDB containers to communicate.

docker network create mongo-cluster

Step 2: Start MongoDB Containers

Next, start your MongoDB containers with the necessary configuration for replication. You'll need at least three containers for a typical replica set (one primary and two secondaries).

docker run -d --name mongo-primary --net mongo-cluster mongo mongod --replSet myReplicaSet
docker run -d --name mongo-secondary-1 --net mongo-cluster mongo mongod --replSet myReplicaSet
docker run -d --name mongo-secondary-2 --net mongo-cluster mongo mongod --replSet myReplicaSet

Step 3: Configure the Replica Set

Once all containers are running, configure the replica set by connecting to one of the MongoDB instances and initiating the replica set.

  1. Connect to the primary container:
docker exec -it mongo-primary mongo
  1. In the MongoDB shell, initiate the replica set with the following command:
rs.initiate({
  _id: 'myReplicaSet',
  members: [
    { _id: 0, host: 'mongo-primary:27017' },
    { _id: 1, host: 'mongo-secondary-1:27017' },
    { _id: 2, host: 'mongo-secondary-2:27017' }
  ]
})

This configures the replica set with one primary and two secondary nodes based on the containers you started.

Additional Notes

By following these steps, you've successfully set up a basic MongoDB replica set running on Docker. This setup is suitable for development and testing, but remember to adjust configurations and security settings according to your production requirements.

Was this content helpful?

Help us improve by giving us your feedback.

Other Common MongoDB Performance Questions (and Answers)

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

System Design on AWS

Switch & save up to 80%

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost