【问题标题】:Connect to docker postgres from golang application从 golang 应用程序连接到 docker postgres
【发布时间】:2021-07-14 16:34:30
【问题描述】:

我正在尝试从 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

我可以从 pgadmin docker 容器连接到这个数据库:docker run --rm -p 5050:5050 thajeztah/pgadmin4 使用 docker inspect my-postgres 命令返回的 IP 地址作为 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.

转码:

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

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

【问题讨论】:

    标签: postgresql docker go


    【解决方案1】:

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

    如果:

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

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

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

    【讨论】:

    • 我将主机更改为“localhost”,但它说 pq: 数据库“mytestdb”不存在,虽然它在 psql 数据库列表中列出名称 |所有者 |编码 |整理 |类型 |访问权限-----------+------------+----------+------------+- -----------+----------- mytestdb |后勤 | UTF8 | en_US.utf8 | en_US.utf8 |
    • 这可能是因为我的本地 Postgres 服务器上没有 mytestdb 数据库。如何改为指向 docker postgres 容器?
    猜你喜欢
    • 2018-03-18
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    相关资源
    最近更新 更多