【发布时间】: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