4

I have deployed MongoDB ReplicaSet on Kubernetes using Helm and the chart stable/mongodb-replicaset

On Kubernetes, I can connect to MongoDB using the connection string which is something of the sort

mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl

In the event I change the number of replicas, the connection string would change as well, which also means that every application connecting to the database would need to be updated.

Is there a workaround to this?

I thought of creating a Service, so that only this would need to be changed, however the connection string does not pass regex validation.

Any help on this is appreciated.

GZZ
  • 628
  • 9
  • 18

2 Answers2

4

The Helm chart stable/mongodb-replicaset deploys also 2 headless services:

  1. <release name>-mongodb-replicaset
  2. <release name>-mongodb-replicaset-client

The DNS record of <release name>-mongodb-replicaset returns the address of all the replicas, so, in order to connect to the replicaset, the connection string is

"mongodb+srv://<release name>-mongodb-replicaset.namespace.svc.cluster.local/?tls=false&ssl=false"

Note that tls and ssl have been set to false for testing as they were enabled by default.

GZZ
  • 628
  • 9
  • 18
0

The drivers will discover all nodes of a replica set automatically. If you are only changing the total number but the first one always has the same address, you can specify just the first node's address in the connection string.

Depending on the driver this may or may not connect to the replica set (as opposed directly to that one node), which generally has two solutions:

  1. Add replicaSet option to the URI.
  2. Provide first two node addresses.

Alternatively, you can set up SRV records and use an SRV URI which is how MongoDB Atlas works. This applies to all topologies (including sharded clusters, which replica set discovery does not apply to).

D. SM
  • 13,584
  • 3
  • 12
  • 21
  • Correct me if I am wrong, but unless you specify all MongoDB nodes, you are not 100% sure you are hitting the Primary right? (for example in the case the node goes down and another one gets elected as primary). Regarding the SRV records option, could you elaborate a bit more (or point me in the right direction) on how this could be implemented? – GZZ Apr 29 '20 at 10:04
  • The driver discovers the primary from information provided by replica set nodes. If it cannot locate a primary, or if there is no primary in the deployment, operations which require a primary (such as writes) will fail. SRV documentation is linked in the answer. – D. SM Apr 29 '20 at 15:19
  • Thanks for your help @Oleg. I finally managed to get this working. The [answer](https://stackoverflow.com/a/61514163/12400174) was quite simple in the end. – GZZ Apr 30 '20 at 00:58