MongoDB Tutorial - How To Deploy A MongoDB Replica Set or Cluster Using Docker
MongoDB Tutorial - How To Deploy A MongoDB Replica Set or Cluster Using Docker
Watch on
Introduction
In this tutorial, we will learn how to deploy a MongoDB replica set or cluster using Docker. MongoDB replica set
ensures that your data is backed up and available in case of hardware or software failure. To create a replica set, you
need at least three nodes, with one acting as the primary node. The primary node handles all the reads and writes,
while the secondary nodes act as backups or standby nodes.
Verify that the network has been created by running the command:
docker network ls
Here, we are mapping the internal port 27017 of the container to the external port 130001. The container is attached
to the network "net" and given the name "m1". We are using the image version 4.0.4 and specifying the replica set
name as "set".
Create the second and third containers using the following commands:
docker run -d -p 130002:27017 --network=net --name m2 mongo:4.0.4 --replSet set
docker run -d -p 130003:27017 --network=net --name m3 mongo:4.0.4 --replSet set
Make sure to change the external port and container name for each command.
docker ps
Inside the container, create a variable named "config" and set it to the configuration of the replica set. The
configuration should specify the replica set name and the members (nodes) of the replica set. For example:
config = {
_id: "set",
members: [
{ _id: 0, host: "m1:27017" },
{ _id: 1, host: "m2:27017" },
{ _id: 2, host: "m3:27017" }
]
}
rs.initiate(config)
This command will initialize the replica set using the configuration specified in the "config" variable.
rs.status()
This command will display detailed information about the replica set, including the state of each node. The primary
node will have the state "PRIMARY", while the secondary nodes will have the state "SECONDARY".
Now, let's simulate a failover by stopping the primary node (m1). After stopping the node, one of the secondary
nodes will become the new primary. To stop the node, use the following command:
docker stop m1
After stopping the node, log in to one of the secondary nodes (e.g., m2) and check the status of the replica set using
the command "rs.status()". You should see that the secondary node has become the new primary.
By setting up a replica set with multiple nodes, you can ensure that your data remains accessible even in case of
hardware or software failures. The secondary nodes act as backups or standby nodes, ready to take over as the
primary node if necessary.
Conclusion
In this tutorial, we have learned how to deploy a MongoDB replica set or cluster using Docker. Replica sets provide
data backup and availability in case of failures. By following the steps outlined in this tutorial, you can easily set up
and configure a MongoDB replica set using Docker.