sqlx.Connect() get stuck in docker alpine:latest

807 views Asked by At

I have problem that I've managed to reduce to the following code:

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")
    }
}

I set up a repo with the code and more explanations at:

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

When I build and run this Go code with a valid DB url in a docker image (here golang:latest) throught docker-compose, where both the above program and the postgres db is in separate containers, the program runs as expected:

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

However, when I run the same program in same setup (docker-compose) with the base image alpine:latest, the program just gets stuck at the sqlx.Connect():

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

I have no idea why this is. Do you know? I have setup a project to see if others can reproduce and get the same problem as I get:

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

Love to hear some insights that can help me solve this issue.

My system details:

  • macOS 10.12.6 (Sierra, MBP Mid 2015 15-inch)
  • docker 17.06.1 1-ce-mac24
1

There are 1 answers

0
mraxus On

Proper solution (by realizing the actual problem)

So it turns out that the corporate network at work have a search domain set. This affects the alpine containers name resolution. However, the default golang is not.

To solve the problem, you can overwrite docker-compose containers search domain, by modifying the config:

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

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

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

Alternative solution (not having realized the actual problem)

By forcing go to use the cgo name resolver, there is no longer any issues:

In docker-compose.yml

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

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

It should be mentioned that this solution is still iffy. In our real dev environment, containing ~20 services configured in docker-compose, some docker alpine images still did not resolve properly. But when updating the configuration with the "proper solution", everything worked like a charm.