所以我有一个
docker-compose.yaml
services:
db:
image: postgres
ports:
- "5432:5432"
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: test
networks: [ "test_network" ]
app:
build: .
ports:
- "8080:8080"
environment:
DB_HOST: db
DB_USER: user
DB_PASSWORD: password
DB_NAME: test
depends_on:
- db
networks: [ "test_network" ]
networks:
test_network:
driver: bridge
在我的 golang 应用程序代码中,我尝试像这样连接到数据库,
db, err := gorm.Open(postgres.New(postgres.Config{
DSN: "host=db user=user password=password dbname=test port=5432",
PreferSimpleProtocol: true, // disables implicit prepared statement usage
}), &gorm.Config{})
当我做
docker-compose up
时,它失败了,
[error] failed to initialize database, got error failed to connect to `host=postgres user=user database=test`: hostname resolving error (lookup postgres on 127.0.0.11:53: read udp 127.0.0.1:36942->127.0.0.11:53: i/o timeout)
news-api-app-1 | 2023/04/08 07:16:38 Cannot run server, encountered an error whilst initializing - failed to connect to `host=postgres user=user database=test`: hostname resolving error (lookup postgres on 127.0.0.11:53: read udp 127.0.0.1:36942->127.0.0.11:53: i/o timeout)
对于初学者,当我在应用程序代码中明确提到
host=postgres
时,为什么它连接到host=db
?为什么会失败?
从
psql
我能够连接到数据库。
应该怎么做才能解决这个问题?
哦所以问题是我已经更改了主机但没有进行重建,重建解决了问题。