连接Docker上的PostgreSQL被拒绝

4

我正试图通过psycopg2连接postgres docker容器,但一直收到相同的错误。

我在jupyter(docker容器)上进行此操作,我多次重启postgres容器并更改postgresql.configlisten_addresses = '*'listen_addresses = 'localhost',但仍出现相同错误。

这是docker运行命令:

docker run --name postgres -e POSTGRES_PASSWORD=xxxxxxx -d -p 5432:5432 -v $HOME/docker/volumes/postgres:/var/lib/postgresql/data  postgres

python

import psycopg2 as pg
connection = pg.connect("host=localhost dbname=easy_cleaning user=root")

我希望连接,但是我遇到了这个错误:

----> 3 connection = pg.connect("host=localhost dbname=easy_cleaning user=root")

/opt/conda/lib/python3.7/site-packages/psycopg2/__init__.py in connect(dsn, connection_factory, cursor_factory, **kwargs)
    124 
    125     dsn = _ext.make_dsn(dsn, **kwargs)
--> 126     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
    127     if cursor_factory is not None:
    128         conn.cursor_factory = cursor_factory

OperationalError: could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?

1
如果您能分享您正在使用的docker运行命令或docker-compose文件,那将会很有帮助。这很可能是容器端口映射的问题。 - Bouzid Zitouni
我在上面更新了它。 - Lucas
1
尝试连接主机的 IP。输入 docker inspect postgres 命令(其中 postgres 是容器名称),并查找 IPAddress。否则,您可以使用 docker-compose 并使用服务名称作为主机(但请注意 API 和数据库应在同一网络上)。 - Vasileios Pallas
谢谢,就是这样,现在可以工作了。 - Lucas
1个回答

2
在您的配置中,您的容器不在本地主机上,Docker为其创建了一个私有IP。因此,您需要运行以下命令:
最初的回答:
在您的配置中,容器不在本地主机上,Docker为其创建了一个私有IP。因此,您需要运行以下命令:
docker inspect postgres

在连接中查找IPAddress字段,将其用于连接:

最初的回答:

connection = pg.connect("host=<DOCKER_IP_ADDRESS> dbname=easy_cleaning user=root")

最初的回答

您可以使用docker-compose将您的镜像作为服务运行,每个服务都有一个名称,在连接中可以用作主机名,例如:

connection = pg.connect("host=postgres dbname=easy_cleaning user=root")

最初的回答

在这里阅读更多内容


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