0

I have a working setup of Spring boot application connecting to Postgres DB in docker. The same Spring boot application throws an exception when I move it to another docker container. The Postgres docker was unchanged. What might be wrong ? Why is the same application working outside docker and not connecting to Postgres when put inside docker.

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

application.properties

spring.datasource.url=jdbc:postgresql://MYDOMAIN:5432/

UPDATE

When I changed MYDOMAIN to the public IP address of the machine hosting Postgres docker, it worked fine. But why is the domain name not getting resolved ?

Krishnan V S
  • 1,124
  • 1
  • 13
  • 31

2 Answers2

0

Because a Docker Container is an isolated environment which you only have your spring boot application in it. so inside that container, there are no Postgres running on port 5432.

you can follow the instruction in this link to create a docker-compose file in which you can address the PostgreSQL Docker Container in that file to your dockerized spring boot application.

  • Thanks for your reply. But what I am not clear about is that I am not using "localhost", I am using FQDN to access Postgres. Can the docker container not make external call and access the DB ? The link you shared has both Spring Boot and PG in the same docker-compose but that is not what I need - I have an existing PG Docker container to which my Spring boot app has to connect to. It connects fine outside of docker but when moved into docker, it does not connect. – Krishnan V S Jan 07 '23 at 14:11
  • Use --network="host" in your docker run command, then 127.0.0.1 in your docker container will point to your docker host. Refer to the answers in [this post](https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach/24326540#24326540). – m.zolfaghari Jan 07 '23 at 14:32
0

I could find the root cause finally. From /etc/hosts file, when I removed MYDOMAIN against 127.0.0.1, the spring boot application was able to resolve MYDOMAIN via internet and access Postgres.

Krishnan V S
  • 1,124
  • 1
  • 13
  • 31