【问题标题】:Docker container Postgres connection errorDocker 容器 Postgres 连接错误
【发布时间】:2017-09-05 17:37:47
【问题描述】:

我一直在为 postgres 试用 docker 容器。到目前为止,我还无法连接到容器内的数据库。

我在下面重现问题的步骤。

dockerfile 启动

FROM postgres
ENV POSTGRES_DB db 
ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD postgres
COPY db_schema.sql /docker-entrypoint-initdb.d/

我是这样构建 docker 文件的

$ docker build -t db_con .

并创建了一个容器

$ docker run -it -p 5432:5432  --name test_db db_con /bin/bash

运行容器如下图

$ docker ps -a

CONTAINER ID    IMAGE   COMMAND                  CREATED       STATUS       PORTS                    NAMES
82347f1114c4    db   "docker-entrypoint..."      3 hours ago    Up 2 sec    0.0.0.0:5432->5432/tcp   test_db

我检查了容器中的地址信息..

$ docker inspect test_db

--extract start--
"Networks": {
                "bridge": {
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",

                }
            }
--extract end--

现在,我在容器内尝试过,但没有成功。 我已经尝试了以下所有命令,但出现以下错误。

root@82347f1114c4:/# psql -U postgres -h 0.0.0.0 -p 5432 -d db
root@82347f1114c4:/# psql -U postgres -h 172.17.0.1 -p 5432 -d db
root@82347f1114c4:/# psql -U postgres -h 172.17.0.2 -p 5432 -d db
**response for all the above**
psql: could not connect to server: Connection refused
    Is the server running on host "0.0.0.0" and accepting
    TCP/IP connections on port 5432?

如果有人能指出我正确的方向,我会很高兴。我在这里碰壁了,非常感谢任何帮助。

【问题讨论】:

  • 尝试所有这些东西,例如创建模式、从外部连接到数据库实例(即在容器生命周期之外)。这是更有用的方法。

标签: postgresql docker containers dockerfile psql


【解决方案1】:

您似乎将默认 postgres cmd 覆盖为 /bin/bash。 为什么要在命令末尾加上/bin/bash

docker run -it -p 5432:5432  --name test_db db_con /bin/bash

尝试执行

docker run -it -p 5432:5432  --name test_db db_con

另外,postgres 仅在 db dump 恢复后才可用。

【讨论】:

  • 回答正确,一切都按照您的建议完美运行。
【解决方案2】:

您需要在 pg_hba.conf 中添加新规则:

nano /etc/postgresql/9.3/main/pg_hba.conf

添加:

host    all             all             [Docker Server IP]/16            md5

接下来,您需要取消注释 postgres.conf 中的以下行:

listen_addresses = '*'                  # what IP address(es) to listen on;

现在重新启动您的 postgres 服务,然后重试。

【讨论】:

    猜你喜欢
    • 2019-10-08
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2021-02-22
    • 2019-03-16
    相关资源
    最近更新 更多