Hi,
I’ve installed Percona Server for MongoDB using the official operator. I noticed that by default, a headless ClusterIP service is created that points to all MongoDB replicas.
I also saw that it’s possible to enable the creation of a service for each replica using the following configuration:
replsets:
rs0:
expose:
enabled: true
My question is: what is the recommended way to connect to MongoDB and ensure a reliable connection?
Should I use a connection string like this, pointing to the headless service:
mongodb://username:password@mongodb-rs0:27017/?replicaSet=rs0
Or should I explicitly list all replicas, like this:
mongodb://username:password@mongodb-rs0-0:27017,mongodb-rs0-1:27017,mongodb-rs0-2:27017/?replicaSet=rs0
Which approach is considered best practice in a Kubernetes environment with Percona Server for MongoDB?
Thanks in advance for your advice!
1 Like
Hi, I would suggest using all the replicas. If one pod goes down, new connections can still reach mongodb. You can read more here Exposing the cluster - Percona Operator for MongoDB
Hi Ivan,
thanks a lot for the advice. I wanted to ask if, by customizing the CR, it is possible to configure the creation of both ClusterIP services (including for each replica) and NodePort services? In some cases, it might be useful for me to access the database from outside the cluster.
No problem. If you set the type to create NodePort service, then ClusterIP service also should be created.
When setting the type to NodePort, what actually happens is that the operator creates 3 NodePort services, one per replica. The only ClusterIP service that remains is the headless service, which, as you mentioned before, should not be used for client connections because you recommended connecting to all three replicas explicitly.
Therefore, I understand that I need to create the NodePort services myself if I want external access, is that correct?
Thanks again for your support!
Sorry if I confused you, the ClusterIP service is fine to use internally. In the first example you posted:
mongodb://username:password@mongodb-rs0:27017/?replicaSet=rs0
I thought you were trying to connect to a single pod.
Using the headless service would be something like:
mongosh "mongodb://username:password@mycluster-rs0.<namespace name>.svc.cluster.local/admin?replicaSet=rs0"
So using headless Cluster IP service, I get the same result as this?
mongodb://username:password@mongodb-rs0-0:27017,mongodb-rs0-1:27017,mongodb-rs0-2:27017/?replicaSet=rs0
Yes, since the service maps to each of the pod endpoints
1 Like