postgresql - 无法将Go Application连接到docker-compose中的postgres容器

标签 postgresql docker go docker-compose

我一直在尝试使用docker-compose将go应用程序连接到postgresql db。
这是我用于Web服务器的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 db,因为它给出了来自的连接拒绝错误消息
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服务器容器无法在其网络外部连接) 。
我该如何纠正?

最佳答案

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

关于postgresql - 无法将Go Application连接到docker-compose中的postgres容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63481240/

相关文章:

windows - 如何在Windows 10 上准备Cygwin 环境来编译Ada GNATColl 库

postgresql - 使用 NHibernate 映射复合键时出现问题(列已添加)

postgresql - Postgres 递归 json 限制

docker - Kubernetes从容器访问标签

docker.io 命令仅替换为 'docker'

json - 不正确的 JSON 被解码为没有错误的结构

linux - 如何在/mnt/中创建文件读/写权限?

SQL:选择不同的左边

Docker Compose CLI 标志

go - 如何检查从 golang 中的 tabwriter.Writer 返回的响应