I am trying to connect my PostgreSql database within Symfony and Docker and getting an error:
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
And .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?
I evan edited my /etc/hosts file to connect this host to 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.
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)
sth like this (in symfony service definition)
environment:
- DATABASE_URL="postgresql://root:root@db/my_db?serverVersion=12&charset=utf8"
where "db" is your service name for postgres
I had similar issue and for me this alias helped.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.