Kubernetes share Mongodb variables with NodeJS via environment

9/8/2017

I have a simple setup in kubernetes hosting a NodeJS application using deployment + service and a mongo with its own deployment + service available in the same kubernetes cluster.

My problem is how do I get the mongo ip into my nodeJS env file as : DB_URL=mongo:27017/test via mongo´s kubernetes env to the nodeJS app ENV?

I assume the Service IP for mongo is not constant and may change.

-- SamTheGoodOne
kubernetes
mongodb
node.js

3 Answers

9/8/2017

you can't base your connection on POD IP. You should either stick to service (preferably by using the service name) or consider StatefulSet that will make it possible to always reach your mongo 1st pod as mongo-1 or something like that

-- Radek 'Goblin' Pieczonka
Source: StackOverflow

9/10/2017

One way would be to specify your own cluster IP address as part of a Service creation request. To do this, set the spec.clusterIP field. The IP address that a user chooses must be a valid IP address and within the service-cluster-ip-range CIDR range that is specified by flag to the API server

Another menthod would be enable DNS throughout the cluster then all Pods should be able to do name resolution of Services automatically. For example, if you have a Service called "my-service" in Kubernetes Namespace "my-ns" a DNS record for "my-service.my-ns" is created. Pods which exist in the "my-ns" Namespace should be able to find it by simply doing a name lookup for "my-service". Pods which exist in other Namespaces must qualify the name as "my-service.my-ns". The result of these name lookups is the cluster IP.

https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services

-- Innocent Anigbo
Source: StackOverflow

9/9/2017

You can access service host/ports as so:

this.url = 'mongodb://'
+ process.env.MYAPP_TRANSACTIONS_MONGO_SERVICE_HOST + ':'
+ process.env.MYAPP_TRANSACTIONS_MONGO_SERVICE_PORT;

Read more in the docs here

You can print your env variables for a given service with this command:

kubectl exec myapp-deployment-3599435869-fn70t   -- printenv | grep SERVICE
-- SamTheGoodOne
Source: StackOverflow