3

我有一个问题,我设法减少到以下代码:

package main

import (
    "fmt"
    "github.com/jmoiron/sqlx"
    _ "github.com/lib/pq"
    "os"
)

func main() {
    addr := os.Getenv("DB")
    fmt.Println("Postgres addr: " + addr)

    _, err := sqlx.Connect("postgres", addr)

    if err != nil {
        fmt.Println("Could not connect...")
    } else {
        fmt.Println("Connecting successful")
    }
}

我在以下位置设置了一个包含代码和更多解释的存储库:

https://github.com/mraxus/mystery-golang-alpine

golang:latest当我在 docker 映像(此处) throught中使用有效的 DB url 构建并运行此 Go 代码时docker-compose,其中上述程序和 postgres db 位于单独的容器中,程序按预期运行:

build_1     | Postgres addr: postgres://postgres@postgres/postgres?sslmode=disable
build_1     | Connecting successful

docker-compose但是,当我在与基本映像相同的设置 () 中运行相同alpine:latest的程序时,程序会卡在 sqlx.Connect() 中:

alpine_1    | Postgres addr: postgres://postgres@postgres/postgres?sslmode=disable

我不知道为什么会这样。你知道吗?我已经设置了一个项目,以查看其他人是否可以重现并遇到与我相同的问题:

https://github.com/mraxus/mystery-golang-alpine

喜欢听到一些可以帮助我解决这个问题的见解。

我的系统详情:

  • macOS 10.12.6(Sierra,MBP 2015 年中 15 英寸)
  • 码头工人 17.06.1 1-ce-mac24
4

1 回答 1

0

正确的解决方案(通过实现实际问题)

所以事实证明,工作中的公司网络有一个搜索域集。这会影响 alpine 容器名称解析。但是,默认的 golang 不是。

要解决此问题,您可以通过修改配置来覆盖 docker-compose 容器搜索域:

build:
    dns_search: .
    image: image:build
    ...

alpine:
    dns_search: .
    image: image:alpine
    ...

https://github.com/mraxus/mystery-golang-alpine/pull/4

替代解决方案(没有意识到实际问题)

通过强制 go 使用cgo名称解析器,不再有任何问题:

在 docker-compose.yml

alpine:
    image: mamarcus.org/project:alpine
    links:
        - postgres
    environment:
        DB: "postgres://postgres@postgres/postgres?sslmode=disable"
        GODEBUG: "netdns=cgo"

https://github.com/mraxus/mystery-golang-alpine/pull/3

应该提到的是,这个解决方案仍然存在问题。在我们真实的开发环境中,包含在 docker-compose 中配置的大约 20 个服务,一些 docker alpine 图像仍然无法正确解析。但是当使用“正确的解决方案”更新配置时,一切都像魅力一样。

于 2017-09-11T11:32:38.787 回答