sqlx.Connect() 卡在 docker alpine:latest
Posted
技术标签:
【中文标题】sqlx.Connect() 卡在 docker alpine:latest【英文标题】:sqlx.Connect() get stuck in docker alpine:latest 【发布时间】:2018-02-18 08:10:33 【问题描述】:我已经设法将问题简化为以下代码:
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")
我在以下位置设置了一个包含代码和更多解释的 repo:
https://github.com/mraxus/mystery-golang-alpine
当我在 docker 映像(此处为 golang:latest
)到 docker-compose
中使用有效的 DB url 构建和运行此 Go 代码时,其中上述程序和 postgres db 都位于不同的容器中,程序按预期运行:
build_1 | Postgres addr: postgres://postgres@postgres/postgres?sslmode=disable
build_1 | Connecting successful
但是,当我使用基本映像 alpine:latest
在相同的设置 (docker-compose
) 中运行相同的程序时,程序会卡在 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【问题讨论】:
不要从golang:latest
构建 alpine 容器,而是尝试从 golang:alpine
构建。
@SnoProblem 感谢您的建议。好主意。但是,在我看来似乎没有帮助:github.com/mraxus/mystery-golang-alpine/pull/1
感谢 @Flimzy 的修复
这可能是特定于操作系统的,因为这两个图像都适合我。我在 Vagrant VM Ubuntu 16.04 LTS 上运行它们
感谢您检查@TarunLalwani。很高兴知道它适用于其他平台。我将我的系统详细信息添加到问题中。 Docker 刚刚发布了 mac 的更新(17.06.2-ce,构建 cec0b72),但没有任何区别。我会继续我的追求。
【参考方案1】:
正确的解决方案(通过实现实际问题)
事实证明,工作中的公司网络设置了搜索域。这会影响 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 图像仍然无法正确解析。但是,当使用“正确的解决方案”更新配置时,一切都很顺利。
【讨论】:
以上是关于sqlx.Connect() 卡在 docker alpine:latest的主要内容,如果未能解决你的问题,请参考以下文章
pubsub.NewClient 卡在开发机器和 docker 中