Error connecting to Postgres database container

I’m learning Spring with Java and docker and I’ve been using this series of tutorials online.
In this particular tutorial that I’m currently studying, the code compiles without errors and the logs look fine but I can’t seem to connect to the database.

The error that I have is The connection attempt failed. db

Here is the repository with the code that should be working fine:

When I run docker-compose up the code compiles normally, the containers are created but when I use dbeaver to connect the database I get the error.

printscreen of dbeaver error

Any idea why this is happening?

>Solution :

We need to access the postgres service running in a container from the docker host. To achieve this, the solution is twofold:

  • export the container-port on which the postgres process is listening (5432) to the docker host, and
  • connect dbeaver to this port

Export the container-port to the docker host

We can achieve this through the ports keyword in the docker-compose.yml. See the relevant documentation for detail. In the example below, I chose to map the host-port 15432 to the container-port 5432. Depending on what ports are used on the machine, you may want to change the host-port

version: '2'

      - '15432:5432'

Connect dbeaver to the right host and port

Name resolution in a docker network only works for containers in that network. So the host cannot resovlve container-names from the network. Luckly, in the first step we mapped the host-port 15432 to the container-port 5432. Thus, all data sent to 15432 of the local host will be passed along to the container port 5432. Thus, we should configure dbeaver to connect to locahost, port 15432.

Leave a Reply