0

I have a dockerized Go application from which I am trying to access Postgres which is running on localhost (outside the container). When I execute docker run image_name, the following error is thrown:

failed to initialize database, got error failed to connect to host=127.0.0.1:5432 user= database=: hostname resolving error (lookup 127.0.0.1:5432: no such host)

Then Go panics and the application exits.

I use the following to access Postgres:

In main.go:

_ = pflag.String("postgresdb-addr", "host=127.0.0.1:5432 user= database=", "connection string for postgres")

`dbAddr := d.cfg.Get("postgresdb-addr")
 session, err := gorm.Open(postgres.Open(dbAddr.(string)), &gorm.Config{})
 if err != nil {
    return fmt.Errorf("unable to open PostgresDB: %w", err)
 }`

I am using a Docker file to build and run the Go application and when the docker run command executes, it fails and exits because of the Postgres connection failure issue. My Docker file has no mention of Postgres. Postgres is running on localhost outside the container.

Any help would be greatly appreciated. Thanks.

Foobar
  • 843
  • 1
  • 10
  • 23

1 Answers1

0

Instead of localhost, use host.docker.internal to refer to your local machine.