Home > Software design >  How connect to db when running Dockerfile?
How connect to db when running Dockerfile?

Time:10-22

I have a spring boot app that connects fine to my PostgreSQL server running locally in Desktop Docker.

Than I wrote a simple Dockerfile to run my app in container. Container starts but can't connect to my db server with error message:

Connection to localhost:5432 refused.

Why and how to fix this?

CodePudding user response:

To access localhost from inside a docker container you can use the IP of your computer. Localhost or 127.0.0.0 donsen't work.

CodePudding user response:

Use docker compose to connect the two docker containers.

https://docs.docker.com/compose/

On this page you can see an example on how to connect to containers using docker compose:

https://dev.to/mozartted/docker-networking--how-to-connect-multiple-containers-7fl

CodePudding user response:

If they are on seperate Docker networks, use:

docker.host.internal

This connects to the Docker host machine. So if your PostgreSQL instance is exposed on 5432, docker.host.internal will route to that instance through the host from other containers.

Alternatively, set them up in the same network using docker compose or by creating a network and attaching both containers to them. They can then communicate with container name.

https://docs.docker.com/engine/reference/commandline/network_create/

  • Related