简体   繁体   English

Docker - host.docker.internal" (192.168.65.2) 拒绝连接

[英]Docker - host.docker.internal" (192.168.65.2) refused to connect

I am trying to connect my PostgreSql database within Symfony and Docker and getting an error:我正在尝试在 Symfony 和 Docker 中连接我的 PostgreSql 数据库并收到错误消息:

docker-compose.yml码头工人-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

And .env.dev.local.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 SQLSTATE [08006] [7] 无法连接到服务器:连接被拒绝

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

I evan edited my /etc/hosts file to connect this host to 127.0.0.1我编辑了我的 /etc/hosts 文件以将此主机连接到127.0.0.1

As this is Postgres database that is running on my Docker host, I am using the host.docker.internal, which maps to the host IP on Mac or WindowsUsing 127.0.0.1 or localhost will cause the code to try to connect to the same container running the code, which does not have a database running.因为这是在我的 Docker 主机上运行的 Postgres 数据库,所以我使用 host.docker.internal,它映射到 Mac 或 Windows 上的主机 IP 使用 127.0.0.1 或 localhost 将导致代码尝试连接到同一个容器运行代码,该代码没有运行数据库。

How to solve this?如何解决这个问题?

If Symfony is also running in docker, you can try to define ENV directly in docker-compose.yml and pass postgres "service" name/alias (docker will resolve this name)如果 Symfony 也在 docker 中运行,您可以尝试直接在 docker-compose.yml 中定义 ENV 并传递 postgres “服务”名称/别名(docker 将解析此名称)

sth like this (in symfony service definition)像这样(在 symfony 服务定义中)

 environment:
      - DATABASE_URL="postgresql://root:root@db/my_db?serverVersion=12&charset=utf8"

where "db" is your service name for postgres其中“db”是您的 postgres 服务名称

I had similar issue and for me this alias helped.我有类似的问题,对我来说这个别名有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM