I am trying to connect to docker postgres database from the golang code. Command used to create the postgres container: docker run -d -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=password --name my-postgres -p 5432:5432 postgres To create the database I run:
PS C:\Users\Aylin\Desktop\farmers> docker exec -it my-postgres bash
root@8969058907f8:/# psql -U postgres
psql (13.2 (Debian 13.2-1.pgdg100+1))
Type "help" for help.
postgres=# CREATE DATABASE test_db;
CREATE DATABASE
postgres=# \q
I can connect to this database from pgadmin docker container: docker run --rm -p 5050:5050 thajeztah/pgadmin4 using the IP address returned by docker inspect my-postgres command as Host name/address for a new server in pgAdmin 4
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2", -> host address
However, when I try to connect to the database from the application using the same parameters I'm getting the following error:
[2021-04-20 17:04:43] sql: database is closed
dial tcp 172.17.0.2:5432: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
Go code:
const (
host = "172.17.0.2"
user = "postgres"
password = "password"
dbname = "test_db"
port = 5432
)
func FetchConnection() *gorm.DB {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := gorm.Open("postgres", psqlInfo)
}
How can I make this code work? Thanks