How to consume external MongoDB service in Kubernetes

9/6/2019

I have been setting up a Kubernetes cluster for my work deployment. I have my MongoDB hosted on an external droplet and want to configure external service access.

I am following this tutorial. When I apply the my configuration with kubectl everything seems to be running fine.

My setup service & Endpoint

kind: Service
apiVersion: v1
metadata:
 name: mongo
spec:
 ports:
 - name: mongodb
   port: xxxx
------
kind: Endpoints
apiVersion: v1
metadata:
 name: mongo
subsets:
 - addresses:
     - ip: 159.89.x.x
   ports:
     - port: xxx

I am developing using typescript and this is how I currently set up my DB connection

const MONGO_URI = `mongodb://${config.mongourl}:${config.mongoport}/${config.collection}?authSource=admin`;
 const options ={
    user:`${config.mngusername}`, 
    pass:`${config.mngpassword}`,
    keepAlive: true, 
    keepAliveInitialDelay: 300000,
    useNewUrlParser: true,
    useCreateIndex: true
 }
mongoose.connect(MONGO_URI, options);

My question is, how do I consume the setup service/deploymentsin my code.
thanks

-- Mowzey
kubernetes
mongodb
typescript

1 Answer

9/6/2019

There are many ways to consume an external service, such as:

  1. Hardcoding the IP:Port of the service in your app.
  2. Using environment variables in your app and injecting them through configmaps.
  3. Creating a service/endpoint, ExternalName service, or a service with External IPs. This allows your applications to use Kubernetes' Service Discovery mechanisms.

In your case you can just use:
const MONGO_URI = 'mongodb://mongo/${config.collection}?authSource=admin';
as the name mongo will be mapped to 159.89.x.x:xxx

-- victortv
Source: StackOverflow