Connect to mongodb atlas cluster from a kubernetes pod?

6/13/2021

Unable to connect to mongodb atlas with kubernetes pod. Tried almost everything available on internet, but no luck.

yaml file

apiVersion: apps/v1
kind: Deployment
metadata:
  name: weare-auth-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: weare-auth
  template:
    metadata:
      labels:
        app: weare-auth
    spec:
      containers:
        - name: weare-auth
          image: <docker-username>/weare-auth
          env:
            - name: PORT
              value: "3001"
      restartPolicy: Always
      dnsPolicy: Default
---
apiVersion: v1
kind: Service
metadata:
  name: weare-auth-srv
spec:
  selector:
    app: weare-auth
  ports:
    - name: weare-auth
      protocol: TCP
      port: 3001
      targetPort: 3001

and here's my express code

import mongoose from "mongoose";

import { app } from "./app";

const start = async () => {
  try {
    await mongoose.connect(
      "mongodb://<username>:<password>@test-clus.wpg0x.mongodb.net/auth",
      {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
      }
    );
    console.log("Connected to mongodb");

    const PORT = process.env.PORT || 3001;
    app.listen(PORT, () => {
      console.log(`Listening on port ${PORT}`);
    });
  } catch (err) {
    console.error(err);
  }
};

start();

Here are the logs

Find the screenshot of error logs here

I've masked the credentials. Also I am able to connect to mongodb atlas cluster via shell and Robo3T. Also tried setting up the dnsPolicy like it was mentioned in on the post, but no luck.

Any idea what am I missing here?

-- Ayush Srivastav
kubernetes
mongodb
node.js

0 Answers