Connection refused on connecting to PostgreSQL running in Docker using pgAdmin
Problem
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.
However, I was able to connect to other databases other than localhost
.
Solution
I was missing the point that pdadmin
is running in a separate container, so in that container, there was no database running. If the pdAdmin
was installed on my host machine then, localhost
would correctly point to my database since I was mapping port 5432
of the container to port 5432
of the host machine.
So if I wanted to connect to the database, I had to find the database 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
: