gpt4 book ai didi

database - 如何通过在 postgres 的 pg_hba.conf 文件中指定 docker-compose 主机名来允许连接?

转载 作者:行者123 更新时间:2023-12-02 09:47:22 27 4
gpt4 key购买 nike

我试图通过在服务器的 pg_hba.conf 中指定客户端容器的主机名来允许从一个 Docker 容器到 postgres 容器的连接。文件。 Postgres 的文档表明可以指定主机名,而不是 IP 地址。由于我使用 Docker Compose 来启动两个容器,因此它们应该可以使用 Docker Compose 的 DNS 通过容器名称相互访问。出于安全原因,我不想打开所有 IP 地址,当我最终为其他容器添加访问权限时,在 pg_hba.conf 文件中指定容器名称而不是为每个容器分配静态 IP 地址会容易得多其中。但是,当我尝试执行此操作时,它失败并显示如下消息:
psql: FATAL: no pg_hba.conf entry for host "192.168.208.3", user "postgres", database "postgres", SSL off
这是我正在尝试做的最小可重复示例:

我使用以下 Docker Compose 文件:

version: '3'
services:
postgresdb:
image: postgres:9.4
container_name: postgres-server
ports:
- "5432:5432"
volumes:
- "postgres-data:/var/lib/postgresql/data"
postgres-client:
image: postgres:9.4
container_name: postgres-client
depends_on:
- postgres-server

volumes:
postgres-data:

运行后 docker-compose up ,我exec进入服务器容器并修改 pg_hba.conf文件在 /var/lib/postgresql/data看起来像这样:
host all postgres postgres-client trust

然后我重新启动 postgres 服务器( docker-compose down 然后是 docker-compose up )并加载修改后的 pg_hba.conf从安装的卷。

我执行到客户端容器并尝试连接到 postgres 服务器:
docker exec -it postgres-client /bin/bash
psql -U postgres -h postgres-server postgres

这是我收到如下错误的地方:
psql: FATAL:  no pg_hba.conf entry for host "192.168.208.3", user "postgres", database "postgres", SSL off

我似乎无法在网上找到任何显示如何使其工作的内容。我找到了一些例子,它们只是打开所有或一系列 IP 地址,但没有一个例子可以使用主机名。以下是一些相关的问题和信息:
  • https://www.postgresql.org/docs/9.4/auth-pg-hba-conf.htm
  • Allow docker container to connect to a local/host postgres database
  • https://dba.stackexchange.com/questions/212020/using-host-names-in-pg-hba-conf

  • 关于如何使用 Docker Compose 以我期望的方式使其工作的任何想法?

    最佳答案

    您需要添加 全限定主机名 pg_hba.conf 中的客户端容器.

    host all postgres postgres-client.<network_name> trust

    例如:
    host all postgres postgres-client.postgreshostresolution_default trust

    如果没有定义网络, network_name<project_name>_default .
    默认 project_name是 docker-compose.yml 所在的文件夹。

    要获取网络名称,您也可以调用
    docker inspect postgres-client | grep Networks -A1

    或者
    docker network ls

    获取当前在您的 docker 主机上定义的所有 docker 网络的列表

    关于database - 如何通过在 postgres 的 pg_hba.conf 文件中指定 docker-compose 主机名来允许连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60173448/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com