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
  name: weare-auth-depl
  replicas: 1
      app: weare-auth
        app: weare-auth
        - name: weare-auth
          image: <docker-username>/weare-auth
            - name: PORT
              value: "3001"
      restartPolicy: Always
      dnsPolicy: Default
apiVersion: v1
kind: Service
  name: weare-auth-srv
    app: weare-auth
    - 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(
        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) {


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?

Submit an answer

This textbox defaults to using Markdown to format your answer.

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

Sign In or Sign Up to Answer

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.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

@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,