Application cannot connect to database when dockerized [duplicate]

Solution 1:

Each container has its own network interface with its own localhost. So change how Java points to Postgres:

spring.datasource.url=jdbc:postgresql://localhost:5432/sample

To:

spring.datasource.url=jdbc:postgresql://db:5432/sample

db will resolve to the proper Postgres IP.


Bonus. With docker-compose you don't need to build your image by hand. So change:

web:
  image: myuser/manager:latest

To:

web:
  build: .

Solution 2:

I had the same problem and I lost some time to understand and solve this problem:

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

I show all the properties so that everyone understands.
application.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/testdb
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL82Dialect
spring.jpa.hibernate.ddl-auto=update

docker-compose.yml:

  version: "3"
  services:
    springapp:
      build: .
      container_name: springapp
      environment:
        SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/testdb
      ports:
        - 8000:8080
      restart: always
      depends_on:
        - db
    db:
      image: postgres
      container_name: db
      environment:
        - POSTGRES_USER=postgres
        - POSTGRES_PASSWORD=postgres
        - POSTGRES_DB=testdb
        - PGDATA=/var/lib/postgresql/data/pgdata
      ports:
        - 5000:5432
      volumes:
        - pgdata:/var/lib/postgresql/data
      restart: always
  volumes:
    pgdata:

For start spring application with local database we use url localhost.
For connect to container with database we need change 'localhost' on your database service, in my case 'localhost' to 'db'.

Solution: add SPRING_DATASOURCE_URL environment in docker-compose.yml wich rewrite spring.datasource.url value for connect:

  environment:
    SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/testdb

I hope this helps someone save his time.