Postgresql connection with gorm dial error cannot assign requested address

Viewed 2271

I'm trying to use the new gorm v2 implementation with Postgresql (I use Docker for the Golang app and for Postgres). I tried to do it as shown in the gorm documentation.

That gave me the following error:

web_1 | 2020/09/19 19:25:57 /go/src/caiqueservice/main.go:36 failed to connect to host=/tmp user=admin database=caique: dial error (dial unix /tmp/.s.PGSQL.5432: connect: no such file or directory)

So since the documentation didn't specify host, but the error message set that to /tmp I set that value.

dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=disable",
    os.Getenv("DB_HOST"),
    os.Getenv("DB_USERNAME"),
    os.Getenv("DB_PASSWORD"),
    os.Getenv("DB_DATABASE"),
    os.Getenv("DB_PORT"),
)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

.env

DB_HOST=localhost
DB_PORT=5432
DB_DATABASE=caique
DB_USERNAME=admin
DB_PASSWORD=password

Doing so gives me the following error message:

web_1 | 2020/09/19 19:36:47 /go/src/caiqueservice/main.go:36 failed to connect to host=localhost user=admin database=caique: dial error (dial tcp [::1]:5432: connect: cannot assign requested address)

The postgres db is reachable by pgadmin. I don't know what to do next and help would be very much appreciated.

1 Answers

Inside a container, localhost refers to the container itself, not to the host machine. If you are using docker-compose, you should be able to connect to the postgres container (from the app container) using the postgres container name as the host name. If you are running both containers separately, you will need to connect them to the same docker network or link them.

Related