【问题标题】:How to connect mongodb in K8s via a go app如何通过 Go 应用在 K8s 中连接 mongodb
【发布时间】:2021-10-18 21:36:46
【问题描述】:

我有一个 mongodb 服务正在运行。我端口转发以在本地访问它,同时,我尝试检查与 go 应用程序的连接。但我收到以下错误。

panic: error parsing uri: lookup _mongodb._tcp.localhost on 8.8.8.8:53: no such host

端口转发:

kubectl port-forward service/mongodb-svc 27017:27017

Go 应用程序:

package main

import (
    "context"
    "fmt"
    //"log"
    "time"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
)

func main() {
    username := "username"
    address := "localhost"
    password := "password"
    // Replace the uri string with your MongoDB deployment's connection string.
    uri := "mongodb+srv://" + username + ":" + password + "@" + address + "/admin?w=majority"
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
    if err != nil {
        panic(err)
    }

    defer func() {
        if err = client.Disconnect(ctx); err != nil {
            panic(err)
        }
    }()

    // Ping the primary
    if err := client.Ping(ctx, readpref.Primary()); err != nil {
        panic(err)
    }

    fmt.Println("Successfully connected and pinged.")
}

【问题讨论】:

  • 无论出于何种原因,您的代码都试图在 Google 的 DNS (8.8.8.8) 上查找 localhost 的 IP 地址。尝试改用127.0.0.1
  • @Zyl 我按照您的建议更改了它。它没有用。 panic: error parsing uri: lookup _mongodb._tcp.127.0.0.1 on 8.8.8.8:53: no such host 实际上我是从 mongo db documentation 获取的代码,我不知道我错过了什么。

标签: go kubernetes


【解决方案1】:

您的客户端正在尝试进行 DNS 服务查找,因为您在 URI 中指定了 +srv 连接类型。停止这样做并改用正确的连接字符串。我们确实支持集群内但不通过端口转发。我怀疑您正在尝试混合和匹配集群内和集群外的教程。你不能那样做。

【讨论】:

    猜你喜欢
    • 2021-11-16
    • 2022-08-08
    • 2019-02-24
    • 2019-05-25
    • 2017-12-02
    • 1970-01-01
    • 2019-01-07
    • 2022-11-17
    • 1970-01-01
    相关资源
    最近更新 更多