Setting up MongoDB Cluster and Replica-Set
In this article, we're going to talk about a few things which are generally used for database load balancing and replicating your data between multiple database servers.
Join the DZone community and get the full member experience.Join For Free
Database replication is a process in which we run a set of database instances that maintain the same datasets and it provides redundancy and promises high availability of database servers. In case your one database falls down then you still will be able to use the other available database from the cluster and have the same datasets that you had in your previous replica.
In this post, I am going to demonstrate the replication setup in MongoDB. If you're using some other database you might need to check if your database supports replication or not.
Setting up Mongo Servers
For this purpose, I am going to use application container docker for running three MongoDB instances and we're going to configure the replication between three instances. The replication works this way.
As you can see the structure, In the replica-sets you have only one primary and many secondary nodes. Read and writes can only be performed on the primary node. While you could allow read from others and write from primary, that's not recommended; let the server handle it. In between these replica-sets, they send a heartbeat to each other to check their health status, In case the primary went down. The server makes one of the secondary nodes as primary during the election.
With that being said, let's get started setting up servers.
Starting Mongo Containers
I am running my containers on a virtual network bridge in my docker container called app-tier. Now, I have three containers running and I have setup their host names in my /etc/hosts file as:
Where the IPs are the machines where my docker containers are running on default mongo port 27014. Now, the first thing you might want to do is to find the IP of your running container. You can do that by typing the following commands.
Once you have the IP of your container let's start setting up the replication.
rs.add('hostIP: port'), pass as many as hosts servers you want to connect in your replica-set. Once you've been connected instead of getting the
> sign you will see something like
rs0:PRIMARY> which means the server has assigned the replica node. Once you've written anything in one database, the changes will be sync between the members of the replica.
Opinions expressed by DZone contributors are their own.