无法从我的Docker容器连接到本地PostgreSQL服务器

0 投票
1 回答
46 浏览
提问于 2025-04-11 22:27

我正在尝试从我的 Docker 容器连接到本地的 PostgreSQL 服务器。我的操作系统是 Ubuntu 22.04.4。

这是我的 docker-compose.yml 文件。

version: '3'

services:
    ...
    backend:
        build:
            context: '.'
            dockerfile: 'Dockerfile'
        ports:
            - '8000:80'
            - '8001:8001'
        env_file:
            - .env-docker
        image: backend-django:latest
    ...

这是我的 .env-docker 文件。

DEBUG=True
SECRET_KEY=******
DATABASE_USER=postgres
DATABASE_NAME=postgres
DATABASE_PASSWORD=postgres
DATABASE_HOST=host.docker.internal
DATABASE_PORT=5432

这是我的 Dockerfile 文件。

FROM python:3.11
ENV PYTHONBUFFERED 1

...

EXPOSE 8000
CMD ["gunicorn", "-b", "0.0.0.0", "config.wsgi"]

在 Windows 上这个连接是可以的,但在 Ubuntu 上就不行了。

这和 PostgreSQL 有关系吗?我使用的是相同版本的 PostgreSQL,并且可以通过 PgAdmin 连接到本地的 PostgreSQL。

我该如何从我的 Docker 容器连接到 PostgreSQL 服务器呢?

(我在我的 Docker 容器的 docker-compose.yml 中添加了这个内容(来自这篇帖子 - 如何从 Docker 容器内部连接到宿主机的 localhost?),但仍然无法连接。)

extra_hosts:
    - "host.docker.internal:host-gateway"

)

1 个回答

1

把这个添加到你的容器里,在 docker-compose.yml 文件中。

extra_hosts:
    - "host.docker.internal:host-gateway"

如果你一直遇到错误,可以在 postgresql.conf 文件中修改 listen_addresses。

listen_addresses = '*'

然后在你的 pg_hba.conf 文件中添加这些行。

host    all all 0.0.0.0/0   scram-sha-256
host    all all ::/0    scram-sha-256

完成这些后,重启一下 postgresql 服务。

sudo systemctl restart postgresql

撰写回答