How to access mongodb replicaset hosted on a kubernetes cluster from outside? How to access mongodb replicaset hosted on a kubernetes cluster from outside? kubernetes kubernetes

How to access mongodb replicaset hosted on a kubernetes cluster from outside?


  1. run kubectl get services -n <namespace>. this will list the replicaset service
  2. execute kubectl port-forward svc/mongodb-replicaset -n mongoNamespace 27018:27017

where

mongodb-replicaset = mongodb service name

mongoNamespace = namespace

and 27018 = your local port

As best practice, you should always connect on services not on pods. Since pods are automatically recreated/restarted, it will give you a new pod name. Connecting to a service saves you from reconnecting and finding the primary pod of your mongodb replicaset.


kubectl port-forward mongodb-replicaset-0 --namespace mongodb-replicaset 27017:27017

mongodb-replicaset-0 - pod that runs primary set.

This forwards the traffic to localhost:27017 on your machine.

Github discussion

Documentation on port-forward


After you execute kubectl get pods, you will see the name of your pods.

You can connect to any pod using this command: kubectl exec -it POD_NAME /bin/bash. Also check docs for Execute a command in a container.

Also, after connecting to a POD, you can check where is mongo located using whereis mongo.

I think default installation is located at /usr/bin/mongo, so while being connected to your cluster you can call mongo directly from any pod you like using kubectl exec -it POD_NAME /usr/bin/mongo.