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 .

2
  • 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: stackoverflow.com/questions/60109913/… baeldung.com/spring-boot-postgresql-docker Commented Aug 11, 2021 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. Commented Aug 11, 2021 at 13:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.