Kubernetes connect to MongoDB atlas issue error parsing uri: lookup on 10.96.0.10:53: no such host

3/17/2020

I use MongoDB atlas as my database service and I have no problem with connecting to it in simple localhost or using running as a docker image. However, when I try to deploy it to kubernetes, I keep encountering the following issue:

error parsing uri: lookup _mongodb._tcp.xxxxdb-tryqz.azure.mongodb.net on 10.96.0.10:53: no such host

After some research, I know that some more configuration (e.g. dnsPolicy on pod setting, expose service with ExternalName type...etc) is required in order to connect to an external dns / ip. Yet, I still having the same issue after different trial.

Trial 1: dnsPolicy

I added dnsPolicy in my deployment.yaml but still not working.

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-api-deployment
  labels:
    app: my-api
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-api
  template:
    metadata:
      labels:
        app: my-api
    spec:
      containers:
        - name: my-api
          image: xxx/my-api:v4
          ports:
            - containerPort: 2322
          env:
            - name: MONGODB_USERNAME
              value: userb
            - name: MONGODB_PASSWORD
              value: abc12345
            - name: MONGODB_HOST
              value: xxxxdb-tryqz.azure.mongodb.net
      dnsPolicy: Default

Trial 2: Using Service

service-deployment.yaml

kind: Service
apiVersion: v1
metadata:
  name: mongodns
spec:
  type: ExternalName
  externalName: xxxxdb-tryqz.azure.mongodb.net

deployment.yaml (Same with above but with the following changes)

  - name: MONGODB_HOST
          value: mongodns

When using the trial 2 method, the error changed accordingly:

error parsing uri: lookup _mongodb._tcp.mongodns on 10.96.0.10:53: no such host

One more wried thing is when I apply the service-deployment.yaml, the service is keep loading in minikube dashboard.

enter image description here

Here is my GoLang Script:

    dbHost      :=  os.Getenv("MONGODB_HOST")
    dbUserName  :=  os.Getenv("MONGODB_USERNAME")
    dbPassword  :=  os.Getenv("MONGODB_PASSWORD")

    ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
    mongoURI    :=  fmt.Sprintf("mongodb+srv://%s:%s@%s/test?retryWrites=true&w=majority", dbUserName, dbPassword, dbHost)
    clientOptions   :=  options.Client().ApplyURI(mongoURI)
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Println("NOT Connected to MongoDB!! (1)")
        log.Fatal(err)
    }
-- Trevor. W
kubernetes
minikube
mongodb-atlas

0 Answers