从 docker-compose 文件连接到 Postgres docker 容器 [重复]

Posted

技术标签:

【中文标题】从 docker-compose 文件连接到 Postgres docker 容器 [重复]【英文标题】:Connecting to Postgres docker container from docker-compose file [duplicate] 【发布时间】:2020-04-27 09:43:37 【问题描述】:

我有 2 个项目。第一个包含这个docker-compose.yml

# pg/docker-compose.yml
version: "3"
services:
  postgres:
    image: postgres
    environment:
      POSTGRES_USER: pguser
      POSTGRES_DB: pg
    ports:
      - "5432:5432"
    volumes:
      - "postgres-data:/var/lib/postgresql/data"
    networks:
      - some_net

volumes:
  postgres-data:

networks:
  some_net:
    driver: bridge

第二个项目有这个 docker compose 文件:

# pg_client/docker-compose.yml
version: "3"
services:
  postgres_client:
    image: tmaier/postgresql-client
    command: postgres://pguser@localhost:5432/pg
    networks:
      - pg_some_net

networks:
  pg_some_net:
    external: true

tmaier/postgresql-client 映像非常简单,它安装了 PostgresSQL 并在构建时运行命令 psql DOCKER_COMMAND。就我而言,这是psql postgres://pguser@localhost:5432/pg

我可以从命令行很好地连接到我的 Postgres 数据库:

$ psql postgres://pgmuser@localhost:5432/pg
psql (12.1)
Type "help" for help.

pg=#

但是当postgres_client 容器尝试连接时(在运行docker-compose up 之后),它说失败了

postgres_client_1  | psql: could not connect to server: Connection refused
postgres_client_1  |        Is the server running on host "localhost" (127.0.0.1) and accepting
postgres_client_1  |        TCP/IP connections on port 5432?
postgres_client_1  | could not connect to server: Address not available
postgres_client_1  |        Is the server running on host "localhost" (::1) and accepting
postgres_client_1  |        TCP/IP connections on port 5432?

在编写我的 Postgres 连接 URI 时,我需要考虑 docker-compose 有什么特别之处吗?

非常感谢任何帮助。

【问题讨论】:

见***.com/questions/34393779/…。可能会帮助你。每个 docker compose 都会建立一个隔离的网络。 @AshharHasan Ahhh 感谢您发现这一点。听起来我需要确保两个 docker-compose 文件位于同一个网络中 @AshharHasan 不幸的是,将容器添加到同一个网络似乎无法解决此问题。 【参考方案1】:

postgres 的主机名应该解析为postgres 而不是localhost。你可以试试

command: postgres://pguser@postgres:5432/pg

【讨论】:

醒了!在引擎盖下看起来 docker 分配了一个单独的 IP 地址(不是 localhost),所以当它在同一个网络中时,我需要引用容器的名称而不是 localhost @bpgeck 那是 docker compose 的事情。它设置主机名。除非您通过 --link,否则不适用于普通的独立容器。

以上是关于从 docker-compose 文件连接到 Postgres docker 容器 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何从 Docker-Compose C# 应用程序连接到本地 SQL Server Express 数据库?

无法从 docker-compose 连接到 docker

如何从 docker-compose 连接到 Host PostgreSQL?

从不同的docker-compose从一个容器连接到另一个容器[重复]

为啥我无法从本地主机上的 Gitlab CI 连接到我的 docker-compose 服务

连接到本地 docker-compose 容器 Windows 10