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

9/13/2018

Cluster created in Rancher with Amazon EKS.

MongoDB replicaset was created as a catalog app in Rancher.

Services in the cluster can successfully connect the the database with this connection string.

mongodb://mongodb-replicaset.mongodb-replicaset.svc.cluster.local:27017/tradeit_system?replicaSet=rs

I want to view and edit data in the db. In a local db you can do it easily by the command mongo --port 27017.

Similarly is there a way to connect to the one one on kubernetes. Either from the terminal or using an application like Robo 3t?

EDIT

The replicaset doesn't show when I do.

kubectl get deployments --all-namespace

kubectl get pods --all-namespaces

Show that it runs in 3 pods mongodb-replicaset-0, mongodb-replicaset-1, mongodb-replicaset-2.

-- enzio902
kubernetes
mongodb
rancher

3 Answers

9/13/2018

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.

-- Crou
Source: StackOverflow

8/7/2019
  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.

-- may
Source: StackOverflow

9/13/2018

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

-- enzio902
Source: StackOverflow