Question

URGENT: How to connect to mongodb atlas cluster from a kubernetes pod?

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

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();

One of the stackoverflow post talked about setting the dnsPolicy, but even after setting it I’m unable to get the connection. Any idea what am I missing here?

Subscribe
Share

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

@meetaayush, the issue is that you’re trying to access your service from outside the cluster using the K8s default service type called ClusterIP. This type of service can only be accessed from within the K8s cluster. Thus, you can use any of the other available options:

  • NodePort (good for development)
  • LoadBalancer (good for development, staging, and production)
  • ExternalName (good for staging and production)

For more on the topic, I recommend referencing the following documentation here.

I wish you all the best and good luck with your project.

Think different and code well,

-Conrad