我正试图通过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?
docker inspect postgres
命令(其中 postgres 是容器名称),并查找IPAddress
。否则,您可以使用 docker-compose 并使用服务名称作为主机(但请注意 API 和数据库应在同一网络上)。 - Vasileios Pallas