Introducing Dragonfly Cloud! Learn More

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

  • Data Persistence: To ensure data persistence across restarts, consider mounting volumes for your MongoDB data directories when starting the Docker containers. Use the -v option in your docker run commands.
  • Configuration Options: The MongoDB Docker image supports various environment variables for customization. For production setups, it's essential to configure authentication, resource limits, and other important settings.
  • Management and Monitoring: Tools like MongoDB Compass or command-line utilities can help manage your replica set and monitor its health and performance.

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?

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.

Free System Design on AWS E-Book

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.