我的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.conf
和postgresql.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
有什么问题?我的容器仍然在日志中运行而没有错误。
答案 0 :(得分:1)
您需要使用-p
选项将localhost的端口映射到容器的端口5432:docker run -p 5432:5432 [Other Options] postgres
。
之后,PORTS
中的docker ps
列应显示如下内容:0.0.0.0:5432->5432