How do you create a mongodb replica set or shard that is externally available in kubernetes?

5/19/2017

I have followed tutorials and set up working mongodb replica sets however when it comes to exposing them as a service I am stuck with using a LoadBalancer which directs to any pod. In most cases this ends up being a secondary database and not terrible helpful. I have also managed to get separate mongodb replicas set up and then tried to connect to those externally however connections fail because internal replicaset ips are all through local google cloud dns.

What I am hoping for is something like this. Mongo Replica in a perfect world

Then (potentially) there is a single connection uri that could connect you to your mongodb replicaset without needing individual mongodb connection details.

I'm not sure if this is possible but any help is greatly appreciated!

-- Alex Wine
google-cloud-platform
kubernetes
mongodb

2 Answers

6/5/2017

The loadbalancer type service will route traffic to any one pod matches its selector, which is not how mongodb replica set works. The connection string should contain all instances in the set. You probably need to expose each replica instance with type=loadbalancer. Then you may connect via "mongodb://mongo-0_IP,mongo-1_IP,mongo-2_IP:27017/dbname_?"

-- Ken Chen
Source: StackOverflow

6/5/2017

If you configure a mongodb replica set with stateful sets, you should also create a headless service. Then you can connect to the replica set with a url like:

“mongodb://mongo-0.mongo,mongo-1.mongo,mongo-2.mongo:27017/dbname_?”

Here mongo-0,mongo-1,mongo-2 are pod names and "mongo" is the headless service name.

If you still want to able to connect to a specific mongo instance, you can create separate service (of type=NodePort) for each of the deployment/replica and then you should be able to connect to a specific mongo instance using <any-node-ip>:<nodeport> But you'll not be able to leverage the advantages of having a mongo replica set in this case.

-- monroe
Source: StackOverflow