首页 > 解决方案 > 为什么我从 python 脚本中得到“psql:服务器意外关闭连接”?

问题描述

我有一个 python 脚本,它首先使用 docker-py 库创建一个 postgres docker 容器:

    client = docker.from_env()
    CONTAINER = 'test_cont'
    container = client.containers.run("postgres", ports={'5432/tcp': 27432},
                                          environment=["POSTGRES_PASSWORD=password",
                                                       "POSTGRES_DB=my_db"],
                                          name=CONTAINER,
                                          detach=True)

docker 容器正确启动。我想从 python 脚本运行一些命令,所以我尝试了:

subprocess.call('psql -h localhost -p 27432 -U postgres -c "CREATE USER xxx WITH PASSWORD \'password\';"', shell=True, env={'PGPASSWORD': 'password'})

但是,此命令总是返回以下错误:

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

如果我从命令行而不是从 python 代码运行 psql 命令,它可以正常工作。

标签: pythondockersubprocesspsql

解决方案


解决了这个问题,如果我们在守护进程模式下运行 postgres docker 容器,它不会等待 postgres 服务器完成启动序列,因此 psql 命令在 postgres 服务器完成启动之前运行。为了解决这个问题,我在 python 脚本中的 docker run 命令之后添加了一个睡眠时间,以允许数据库启动。


推荐阅读