Home > Net >  Docker container image cant access postgresql DB Connection to localhost:5432 refused
Docker container image cant access postgresql DB Connection to localhost:5432 refused

Time:04-27

I'm running a PostgreSQL as a native app(NOT CONTAINER) on my localhost I'm able to connect to it with an SQL client.

While I'm running a spring application - in a container the app starts and fails while trying to connect the database

Caused by: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. 
Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

in my docker image, I have used expose to open the port, but it still won't work

EXPOSE 8080 8443 4000 5432

What can i do to fix it

I run my image with

docker run ec0bdea074a6

Tried also

docker run -p 5432:5432/tcp -p 5432:5432/udp ec0bdea074a6

And it didnt work as well

CodePudding user response:

EXPOSE acts as documentation, just like comments in the Dockerfile. You need to use -p flag in the docker run command. See the docs for more details: https://docs.docker.com/engine/reference/builder/#expose

CodePudding user response:

If both apps are in a container, you should use container networking to establish a connection.

docker network create my-net
docker run --network my-net my-app
docker run --network my-net my-db

Then inside your app code you need to use my-db as hostname instead of localhost.

If you want to connect from your local sql client, you need to publish the db ports and use localhost.

If you want to connect from a service on the host from a container you have 2 options.

# add the gateway as extra host to preverse container networking
# then you have to use host.docker.internal as hostname
docker run --add-host host.docker.internal:host-gateway my-app

# disable docker networking altogether
# then localhost will work
docker run --network host my-app
  • Related