I’ve been having trouble on and off with connecting my app to a postgres container using docker compose. Any attempt at connection from within the shared network times out. For example, trying to run psql -h postgres -U postgres
(or psql postgresql://postgres:unsafe@postgres:5432/postgres
) from another container in the network eventually gives this error after hanging for a couple minutes:
psql: error: connection to server at "postgres" (172.22.0.2), port 5432 failed: Connection timed out
Is the server running on that host and accepting TCP/IP connections?
I am able to successfully connect from outside any docker containers via psql postgresql://postgres:unsafe@localhost:5431/postgres
.
The containers are definitely all within the same network (the default one compose creates for you. Manually defining the network didn’t help either) according to docker network inspect
and all the containers are healthy; no errors or even warnings in the logs.
My setup decides every other day that it will or won’t work at all, so I suspect this issue is not related to my actual docker compose configuration, and is probably something in my environment, but I have no idea where to look, or why it would change from day to day. My coworker also has all the same config options and it works fine on his computer.
Here’s a minimal compose.yaml that I reproduced my issue with (today anyway):
services:
postgres:
build:
context: .
dockerfile: ./docker/postgres/Dockerfile
ports:
# intentionally different since im running postgres locally too
- "5431:5432"
volumes:
- .pgdata:/var/lib/postgresql/data
env_file:
- path: .env
required: false
environment:
- POSTGRES_PASSWORD=unsafe
client:
container_name: postgres-client
image: postgres
environment:
- POSTGRES_PASSWORD=unsafe
And then connecting to the client container with docker exec -it postgres-client /bin/bash
. Any attempt to connect to the other postgres container in the network (e.g. psql postgresql://postgres:unsafe@postgres:5432/postgres
) hangs and then times out.
What more can I do to debug this?