Service Discovery for MongoDB
As renaissancedev blog documentation here In order to build flexible and maintainable cloud infrastructure we need a way to connect services together with minimal effort. For a long time DNS has been the way to do that, but it also poses a different set of problems. How do you keep the DNS entries up to date? How do you make sure that the instances that are registered in DNS are actually healthy and able to serve traffic?

Consul from Hashicorp is a modern answer to these problems that is being widely adopted by teams of all sizes. It is a service discovery layer for your datacenter, as well as being a distributed key-value store and able to perform cross-datacenter replication and discovery. One of the wonderful things about it is the fact that the service discovery layer can be used via a built-in DNS interface. Services that are registered in Consul can have an associated health-check which will cause a failing instance to be removed from the list of DNS entries for that service. All-in-all it’s a pretty great system that is definitely worth considering if you haven’t already started using it yourself.

For Example the Solution of this problem

Once I fully understood what the failure was, the solution became obvious. Since you can register arbitrary service names in Consul and associate a variety of different health checks, all I had to do was set one up that would only point to the node that was currently the master. In order to make that work I wrote a scripted health check that would run the following script every 10 seconds:

#!/bin/bash
ISMASTER=$(/usr/bin/mongo --quiet --eval 'db.isMaster().ismaster')
if [ "$ISMASTER" = "true" ]
then
    exit 0
else
    exit 2
fi


I then configured the Consul agent on the MongoDB instances with this service definition:

{
  "services": [
    {
      "check": {
        "interval": "10s",
        "script": "/consul/scripts/mongo_is_master.sh"
      },
      "name": "mongodb-master",
      "port": 27017,
      "tags": [
        "mongodb",
        "master"
      ]
    }
  ]
}


Whichever instance is passing that check will be registered as the mongodb-master.service.consul DNS record in Consul. That means that the clients just need to be configured to connect to mongodb://mongodb-master.service.consul:27017/database?replicaSet=rs0&amp;readPreference=primaryPreferred and everyone will be happy.

For your further info here and here