无法连接到dockerized数据库,当我尝试从golang服务器连接时,我得到主机名解析错误,应该怎么做?

qpgpyjmq  于 2023-04-09  发布在  Go
关注(0)|答案(1)|浏览(97)

所以我有一个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我可以连接到数据库。应该做些什么来解决这个问题?

qlvxas9a

qlvxas9a1#

哦,所以问题是,我已经改变了主机,但没有做一个重建,重建解决了这个问题。

相关问题