Docker - host.docker.internal" (192.168.65.2) refused to connect。

5

我正在尝试在Symfony和Docker中连接我的PostgreSQL数据库,但是出现了错误:

docker-compose.yml

services:
db:
    image: postgres:${POSTGRES_VERSION:-12}-alpine
    environment:
        POSTGRES_DB: ${POSTGRES_DB:-my_db}
        POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-root}
        POSTGRES_USER: ${POSTGRES_USER:-root}
    volumes:
        - $PWD/postgres-data:/var/lib/postgresql/data:rw
    profiles:
        - db-in-docker
    ports:
        - "5432:5432"
    networks:
        - symfony

还有.env.dev.local

DATABASE_URL="postgresql://root:root@host.docker.internal:5432/my_db?serverVersion=12&charset=utf8"

SQLSTATE[08006] [7] could not connect to server: Connection refused

    Is the server running on host "host.docker.internal" (192.168.65.2) and accepting  
    TCP/IP connections on port 5432?

我修改了我的/etc/hosts文件,将此主机连接到127.0.0.1

由于这是在我的Docker主机上运行的Postgres数据库,我正在使用host.docker.internal,它映射到Mac或Windows主机IP。使用127.0.0.1或localhost将导致代码尝试连接到运行代码的同一个容器,但该容器没有运行数据库。

如何解决?

1个回答

1
如果Symfony也在docker中运行,您可以尝试直接在docker-compose.yml中定义ENV,并传递postgres“service”名称/别名(docker将解析此名称)。
类似于这样(在Symfony服务定义中):
 environment:
      - DATABASE_URL="postgresql://root:root@db/my_db?serverVersion=12&charset=utf8"

在这里,“db”是您的Postgres服务名称。

我遇到了类似的问题,对我来说,使用这个别名有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接