简体   繁体   中英

Kubernetes share Mongodb variables with NodeJS via environment

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM