How to connect to Mongodb from outside Kubernetes cluster

3/12/2020

I need to connect to mongodb external of the kubernetes cluster. I dont know how to do it when i search on internet all the time i found all information about how to connect to mongodb inside the K8s cluster . On the other hand, I wouldn't be against it. but for the begining of the project i'must to connect to external mongodb .

Do you know how to do it ? or do you have any information who can help me ??

deployment.yaml :

  - name: XXXX_CONFIG_API_MONGODB
    value: "mongodb://@IP:27017"

thanks in advance

-- morla
google-kubernetes-engine
kubectl
kubernetes
kubernetes-helm
mongodb

2 Answers

3/12/2020

You need to update service not in deployment. It's service related issue.

apiVersion: v1
kind: Service
metadata:
  name: mongod-db-service
spec:
  selector:
    app: mongod-db
  ports:
    - port: 27017
      targetPort: 27017
  type: LoadBalancer

Note:- "mongod-db" is kubernetes selector that should be same in deployment.

-- ANISH KUMAR MOURYA
Source: StackOverflow

3/12/2020

I need to connect to mongodb external of the kubernetes cluster.

K8s allows a few methods for service to be reachable outside the cluster (namely hostNetwork, hostPort, NodePort , LoadBalancer, Ingress)

This article is so far one of the best on topic.

In general you just need to create a service that'll point to your mongodb.

It can be one of (but not limited to):

  • LoadBalancer type:
kind: Service 
apiVersion: v1 
metadata: 
  name: mongo 
spec: 
  type: LoadBalancer 
  ports: 
    - port: 27017 
  selector: 
    app: my-mongo-db  # this shall match labels from the Deployment
  • NodePort type:
apiVersion: v1
kind: Service
metadata:
  name: mongo
spec:
  selector:
    app: my-mongo-db
  type: NodePort
  ports:
    - 
      port: 27017
      nodePort: 30001 # al the incoming connections to NodeIP:30001 will be forwarded to your mongo-pod

There are more ways to achieve that (just don't want to copy paste here that article I have been referring to).

Hope that helps.

-- Nick
Source: StackOverflow