简体   繁体   中英

Connect to docker postgres from golang application

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

Once you've launched a container with a docker run -p option, to non-container processes, it looks exactly like any other server process that's listening on that port.

If:

  • The host process and Docker container are running on the same host (or in the same VM);
  • You've started the container with a correct -p HOST:CONTAINER port mapping; and
  • You're not running Docker Toolbox or otherwise have Docker in a VM

Then the host process can access the container process using localhost as a host name and the first -p port number.

Never use docker inspect or other means to look up the container-private IP address. It's unreachable in most common setups (it only works if you're on the same native-Linux host; not from other hosts, VMs, or on MacOS or Windows) and is never necessary. Similarly, you shouldn't normally need to use docker exec or other debugging tools to access your database, since you can use normal clients like psql talking to the published port.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM