如何访问使用 docker-compose 设置的 postgresql 数据库?

How do I access a postgresql DB that was setup with docker-compose?

我使用以下 docker-compose.yml 文件:

version: '3.8'

services:
  db:
    image: postgres:13-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    expose:
      - 5432
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=testdb
volumes:
  postgres_data:

我用docker-compose up -d --build提出来。现在,当我尝试从 Python 访问它时,比如说,使用 psycopg2 时,会出现以下错误

>>> conn = psycopg2.connect(host="localhost", database="testdb", user="postgres", password="postgres")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?

>>> conn = psycopg2.connect(host="db", database="testdb", user="postgres", password="postgres")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known

你能帮我解决一下吗?

问题是 expose 没有将端口发布到主机。它们只能由链接服务访问。

您必须手动发布端口:

docker-compose run -d -p 5432:5432 db

而不是使用 expose us this 代替:

ports:
  - "5432:5432"

这定义了到 docker 容器的端口转发

您应该从 docker-compose.yml 文件中删除公开选项并添加端口选项,例如:

ports:
  -"5432:5432"

然后您可以通过主机 localhost 从您的应用程序连接到数据库。