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

问题描述 投票:0回答:1

所以我有一个

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
我能够连接到数据库。 应该怎么做才能解决这个问题?

postgresql docker go docker-compose go-gorm
1个回答
0
投票

哦所以问题是我已经更改了主机但没有进行重建,重建解决了问题。

© www.soinside.com 2019 - 2024. All rights reserved.