所以我有一个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,
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=db
时,为什么它连接到host=postgres
?为什么它失败了?
从psql
我可以连接到数据库。应该做些什么来解决这个问题?
1条答案
按热度按时间qlvxas9a1#
哦,所以问题是,我已经改变了主机,但没有做一个重建,重建解决了这个问题。