【问题标题】:database connection refused数据库连接被拒绝
【发布时间】:2018-05-23 03:48:45
【问题描述】:

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

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 文件,看起来没有什么奇怪的。

附:我也无法通过 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

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

【问题讨论】:

    标签: postgresql docker containers psycopg2 docker-networking


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 2023-03-12
      • 2015-04-13
      • 1970-01-01
      • 2017-08-08
      • 2019-08-04
      相关资源
      最近更新 更多