0

I have created a docker-compose.yml to run a postgresql database . While the image is pulled and can run succesfully I am unable to connect to my database through a spring boot project I have . When I try to run my spring boot project after succesfully running my postgresql container with docker-compose up I get the error org.postgresql.util.PSQLException: The connection attempt failed. and a huge text of error logs underneath where I spotted the cause.

Caused by: java.net.UnknownHostException: postgresqldb

which is the name of my db image .

My docker-compose.yml at the root of my spring project

version: '3.1'
services:
  postgresqldb:
    image: postgres
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_DB=booksdb

My application.properties in my spring boot project .

server.port=8081
server.servlet.context-path=/rest

#Postgres
spring.datasource.url=jdbc:postgresql://postgresqldb:5432/booksdb
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create

#JWT
jwt.secret-key=someKey

I would appreciate your help .

vasilis 123
  • 585
  • 1
  • 12
  • 26
  • Docker has its own network. Springboot does not see your database that is why you oare getting UnknownHostException. Please see for examples on how to do this: https://stackoverflow.com/questions/60109913/docker-compose-error-on-mysql-db-connect-for-spring-boot-app-caused-by-java-net https://www.baeldung.com/spring-boot-postgresql-docker – JCompetence Aug 11 '21 at 13:23
  • If the application is running outside Docker, then the host should be `localhost`; the lines `ports: - "5432:5432"` in docker-compose.yml make sure that port 5432 in the host computer connects to port 5432 inside the Postgres container. When you decide to run the Spring boot application inside Docker, you should use `postgresqldb` as host name. – Nikos Paraskevopoulos Aug 11 '21 at 13:59

1 Answers1

2

Maybe you should add a hostname to the container:

version: '3.1'
services:
  postgresqldb:
    image: postgres
    hostname: postgres
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_DB=booksdb

docker uses its own network and resolves hostname internally. You should assign a hostname to the running container that may be found for the rest of the containers.

Roberto Paz
  • 356
  • 1
  • 8