【发布时间】: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