我正在尝试在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将导致代码尝试连接到运行代码的同一个容器,但该容器没有运行数据库。
如何解决?