docker + golang lib/pq "dial tcp 127.0.0.1:5432: connect: connection refused"

8/28/2019

sql.Open() wouldn't error:

if db, err = sql.Open("postgres", url); err != nil {
    return nil, fmt.Errorf("Postgres connect error : (%v)", err)
}

but db.Ping() would error:

if err = db.Ping(); err != nil {
    return nil, fmt.Errorf("Postgres ping error : (%v)", err)
}

and it was simply because the lib/pq connection string wouldn't connect from within a docker container with the seperated connection parameters.

For example:

url := fmt.Sprintf("user=%v password=%v host=%v port=%v dbname=%v",
    rs.conf.Redshift.User,
    rs.conf.Redshift.Password,
    rs.conf.Redshift.Host,
    rs.conf.Redshift.Port,
    rs.conf.Redshift.DB)
-- Mikeumus
docker
docker-compose
go
kubernetes
postgresql

1 Answer

8/28/2019

Using the connection string as a URL worked:

    url := fmt.Sprintf("postgres://%v:%v@%v:%v/%v?sslmode=disable",
        pql.conf.Postgres.User,
        pql.conf.Postgres.Password,
        pql.conf.Postgres.Host,
        pql.conf.Postgres.Port,
        pql.conf.Postgres.DB)

See lib/pq docs here: https://godoc.org/github.com/lib/pq

I was stuck on this for more than a day and I owe the fix to Nikolay Sandalov's comment here in GitHub: https://github.com/coreos/clair/issues/134#issuecomment-491300639

Thank you, Nikolay ‍♂️

-- Mikeumus
Source: StackOverflow