【问题标题】:Can not connect to Postgres from Python [duplicate]无法从 Python 连接到 Postgres [重复]
【发布时间】:2021-08-14 23:48:32
【问题描述】:

我通过 Dockerfile 使用 Postgres 创建了一个 docker 镜像:

来自 postgres:9.6-alpine

在我启动这个 docker 容器后,我正在检查它是否已启动并使用来自预安装 psql 的不同 docker 容器的连接:

docker run -it --rm --link ml-postgres:postgres postgres:12.2-alpine psql --dbname mlpython -h postgres -U postgres

结果是我能够使用 postgres 连接到第一个容器并使用 postgres 数据库执行所有常规操作。

当我想从本地创建的 Python 脚本连接到带有 postgres DB 的容器时,问题就开始了:

import psycopg2
    
conn = psycopg2.connect(
    host="127.0.0.1",
    database="mlpython",
    user="postgres",
    password="test",
    port="5431"
)
cur = conn.cursor()
    
cursor.execute('SELECT COUNT(*) FROM mytable LIMIT 10')
cur.close()

这是我得到的一个错误:

> psycopg2.OperationalError: server closed the connection unexpectedly
>   This probably means the server terminated abnormally    before or while
> processing the request.

在尝试引导这个 Python 与 Postgres 交互的简单代码示例时,我错过了什么?

【问题讨论】:

  • 当您启动数据库容器时,您需要一个docker run -p 选项才能从Docker 外部访问它;使用该连接字符串,类似于docker run -p 5431:5432 postgres:9.6-alpine(第二个端口号必须是默认端口 5432,但第一个可以是任何值)。

标签: python postgresql docker


【解决方案1】:

请通读您使用的 docker 映像的 README.md。它应该回答你的问题。 我不确定,如果你这样做了,因为:

  1. 我明白了,您启动了 psql - 客户端。为什么,如果你要从 python 连接?您是否启动了服务器?
  2. 我看不到您是否将任何容器端口暴露给主机

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    相关资源
    最近更新 更多