Docker容器连接本地PostgreSQL

4

我运行了Python容器,想要连接本地的PostgreSQL。我尝试了一些方法,但都没有成功。请告诉我该怎么做?谢谢。

我已经在5432端口上运行了PostgreSQL,并创建了数据库和授权用户。

运行Docker命令:

docker run --name=python3 -v ${pwd}:/code -w /code python

Python 代码

import psycopg2

def main():
    #Define our connection string
    conn_string = "host='localhost' dbname='testDB' user='test' password='test'"

    # print the connection string we will use to connect
    print ("Connecting to database\n    ->{}".format(conn_string))

    # get a connection, if a connect cannot be made an exception will be raised here
    conn = psycopg2.connect(conn_string)

    # conn.cursor will return a cursor object, you can use this cursor to perform queries
    cursor = conn.cursor()
    print ("Connected!\n")

if __name__ == "__main__":
    main()

错误信息

服务器是否在本地主机“localhost”(::1)上运行并接受端口5432的TCP/IP连接? 无法连接到服务器:连接被拒绝 服务器是否在本地主机“localhost”(127.0.0.1)上运行并接受端口5432的TCP/IP连接?

3个回答

5
这取决于您的主机操作系统和 Docker 版本。我假设您的数据库不是在容器中运行,而是在主机上(本地主机)。
例如,如 "从 Docker 容器内部连接到机器的本地主机 "中所述,在 Docker for Mac v 17.06 及以上版本(2017 年 6 月),您可以连接到特殊的仅适用于 Mac 的 DNS 名称 docker.for.mac.localhost,它将解析为主机使用的内部 IP 地址。
在 Linux 直接上,您可以使用主机模式,并安装有 ifconfig 的镜像:
docker run --network="host" -id <Docker image ID>

嗨,我尝试运行 docker run --name=python3 -v ${pwd}:/code -w /code --network="host" python,但不起作用。我的操作系统是Windows 10。数据库在本地机器上运行,而不是容器中。谢谢。我还需要做什么吗? - frank
@frank 对于Windows系统,您可以使用桥接网络,并传递Hyper-V IP地址:https://dev59.com/F2Af5IYBdhLWcg3wwk0V#41077351 - VonC
1
@frank 注意:另一个答案是针对在其自己的容器中运行postgreSQL的情况,这不是你的问题。 - VonC
1
@frank,编辑你的问题并指出Postgres运行在Windows虚拟机上会很有用。它不像你最初说的那样在本地主机上运行。 - Robert

1

看到您正在使用Windows 10并在主机上运行postgresql,我建议您在容器中运行postgresql。这样会更容易。

要将python容器连接到postgres容器,您需要一个docker网络。我们称之为postgres_backend。

docker network create postgres_backend

您可以使用以下命令创建postgresql容器。只需将“/path/to/store/data”更改为您想要存储postgres数据的本地目录即可:

docker run --name postgres \
  -e POSTGRES_PASSWORD=test \
  -e POSTGRES_USER=test \
  -d --restart always \
  -v /path/to/store/data:/var/lib/postgresql/data \
  --net postgres_backend \
  postgres:9.6

现在您的postgresql容器应该已经运行成功了 :)
要将您的python容器连接到它,您需要在docker run命令中添加--net postgres_backend,并将脚本中的主机更改为“postgres”(这是我们用--name给postgresql容器命名的名称)。
如果python容器找不到主机“postgres”,请尝试使用输入命令docker exec -ti postgres ip addr show时显示的IP进行尝试。

你好,感谢您的解决方案。我尝试了这种方法,它有效,但我只想连接本地数据库。谢谢。 - frank
也许这个链接可以更有帮助:https://dev59.com/N14c5IYBdhLWcg3wx8pU - samprog

0

修复此错误:

首先,正常情况下它不起作用,因为postgresql不在与应用程序相同的容器中运行,所以主机localhost:5432不存在。 要解决这个问题: 在属性文件中,不要使用localhost:5432,而是使用您的IP地址,例如IP:5432,并在pg_hba.conf中添加以下内容 host all all 0.0.0.0/0 md5


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接