数据库连接被拒绝

database connection refused

我的 PostgreSQL 在 docker 端口 5432 下运行。

docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
f7464f480dd3        postgres            "docker-entrypoint..."   6 hours ago         Up 3 minutes        5432/tcp            core_postgres

这是一个官方的 postgres 容器,创建了一些自定义用户和数据库。

我正在使用 psycopg2 进行连接:

import psycopg2
conn = "host='localhost' dbname='username' user='username' password='password'"
psycopg2.connect(conn)

但它引发了:

Traceback (most recent call last):
  File "check_postgres.py", line 3, in <module>
    psycopg2.connect(conn)
  File "/Users/pivanchy/startup/venv/lib/python2.7/site-packages/psycopg2/__init__.py", line 130, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
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?

我检查了两个:pg_hba.confpostgresql.conf 文件,看起来没有什么奇怪的。

P.S。我也无法通过 telnet 连接到此端口:

telnet localhost 5432

Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
telnet: Unable to connect to remote host

怎么了?我的容器仍然 运行 在日志中没有错误。

您需要使用 -p 选项将本地主机的端口映射到容器的端口 5432:docker run -p 5432:5432 [Other Options] postgres.

之后,docker ps 中的 PORTS 列应该显示如下内容:0.0.0.0:5432->5432