【问题标题】:Can't connect Go Application to the postgres container in docker-compose无法将 Go 应用程序连接到 docker-compose 中的 postgres 容器
【发布时间】:2020-08-19 06:33:48
【问题描述】:

我一直在尝试使用 docker-compose 将我的 go 应用程序连接到 postgresql db。

这是我的网络服务器 Dockerfile

FROM golang:latest

RUN mkdir /app
COPY . /app
WORKDIR /app
RUN go mod download
EXPOSE 5000
CMD ["go","run","main.go"]

这是我的 docker-compose.yml 文件

version: '3'
services:
  db:
    image: postgres:latest
    restart: always
    network_mode: bridge
    environment:
      POSTGRES_USER: factly
      POSTGRES_PASSWORD: qwertyui
      POSTGRES_DB: factly
    ports:
      - "5432:5432"
  server:
    build: .
    depends_on:
      - db
    ports:
      - "5000:5000"

但我无法连接到 postgresql 数据库,因为它给出了来自

的连接被拒绝错误消息
Go serverStarting factly_db_1 ... 
Starting factly_db_1 ... done
Recreating factly_server_1 ... 
Recreating factly_server_1 ... done
Attaching to factly_db_1, factly_server_1
db_1      | 
db_1      | PostgreSQL Database directory appears to contain a database; Skipping initialization
db_1      | 
db_1      | 2020-08-19 06:11:17.151 UTC [1] LOG:  starting PostgreSQL 12.4 (Debian 12.4-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
db_1      | 2020-08-19 06:11:17.151 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1      | 2020-08-19 06:11:17.152 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1      | 2020-08-19 06:11:17.266 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1      | 2020-08-19 06:11:17.906 UTC [26] LOG:  database system was shut down at 2020-08-19 05:56:39 UTC
db_1      | 2020-08-19 06:11:18.213 UTC [1] LOG:  database system is ready to accept connections
server_1  | host=127.0.0.1 port=5432 user=factly password=qwertyui dbname=factly sslmode=disable
server_1  | 2020/08/19 06:11:21 dial tcp 127.0.0.1:5432: connect: connection refused
server_1  | exit status 1
factly_server_1 exited with code 1

我尝试只运行 postgres 容器并将其与运行良好的 Go 应用程序连接,但在容器内运行 Go 应用程序会产生相同的错误(这让我觉得 Go Web 服务器容器无法连接到外部是网络)。 我该如何纠正这个问题?

【问题讨论】:

    标签: postgresql docker go docker-compose


    【解决方案1】:

    我想问题是你试图从 go 程序连接到127.0.0.1,而不是使用数据库容器的主机名db

    【讨论】:

    • 我该怎么做?我试图与主机名 db 连接,但它给出了 dial tcp: lookup db on 127.0.0.11:53: no such host
    • 这可能是因为桥接网络。你可以尝试删除network_mode: bridge吗?
    • 它确实有效。非常感谢。你能描述一下这里发生了什么吗?
    • 默认情况下 docker compose 为每个 compose 项目创建一个新的网络。因此,当您指定特定容器位于不同网络中的不同网络模式时,主机名解析不起作用。因此,当您删除它时,所有容器都在同一个网络中,并且能够通过主机名相互通信。
    最近更新 更多