Connection refused on connecting to PostgreSQL running in Docker using pgAdmin
I was running both my database and the RDBS in a docker container to have all the development tools ready without installing additional software. My Docker compose file looked like this:
version: "3.8"
services:
database:
image: postgres
env_file:
- database.env
volumes:
- database-data:/var/lib/postgresql/data/
ports:
- "5432:5432"
pgadmin:
image: dpage/pgadmin4
ports:
- "5050:80"
env_file:
- dbadmin.env
volumes:
- pgadmin-data:/var/lib/pgadmin
volumes:
database-data:
pgadmin-data:
Then I entered the database details in pgadmin
and tried to connect, which failed.
Solution
I was missing the point that pdadmin
is running in a separate container, so in that container, there was no database running on the localhost
address. However, since they're in the same compose file, by default they're in the same network. I had to use the database service name (database
) in the docker-compose file to point to this container rather than localhost.
There are other ways to point to that container too. You can find the database service IP address and connect to that IP rather than localhost
. To find a container's IP address, inspect the container and find the container network IP address:
docker inspect <postgres_container>
Or you can use host.docker.internal
instead of localhost
: