繁体   English   中英

从 golang 应用程序连接到 docker postgres

[英]Connect to docker postgres from golang application

我正在尝试从 golang 代码连接到 docker postgres 数据库。 用于创建 postgres 容器的命令: docker run -d -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=password --name my-postgres -p 5432:5432 postgres创建数据库我运行:

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

但是,当我尝试使用相同的参数从应用程序连接到数据库时,出现以下错误:

[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 代码:

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)
}

我怎样才能使这段代码工作? 谢谢

一旦你启动了一个带有docker run -p选项的容器,对于非容器进程,它看起来就像在该端口上侦听的任何其他服务器进程一样。

如果:

  • 宿主进程和 Docker 容器运行在同一个宿主(或同一个虚拟机)上;
  • 您已经使用正确的-p HOST:CONTAINER端口映射启动了容器;
  • 您没有在 VM 中运行 Docker Toolbox 或 Docker

然后宿主进程可以使用localhost作为主机名和第一个-p端口号来访问容器进程。

切勿使用docker inspect或其他方式查找容器私有 IP 地址。 它在大多数常见设置中是无法访问的(它仅在您位于同一本机 Linux 主机上时才有效;而不是来自其他主机、VM 或 MacOS 或 Windows 上)并且从不需要。 同样,您通常不需要使用docker exec或其他调试工具来访问您的数据库,因为您可以使用像psql这样的普通客户端与已发布的端口通信。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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