Search code examples
javaspringspring-bootdockerdocker-compose

Unable to establish connection between Spring Boot application running on Docker container and PostgreSQL database running on another Docker container


docker-compose.yml

version: '3.8'
services:
  db:
    image: postgres
    restart: always
    container_name: security-db
    environment:
      POSTGRES_DB: security-db
      POSTGRES_USER: scrty
      POSTGRES_PASSWORD: scrty123
    ports:
      - '5050:5432'

application.properties

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.url=jdbc:postgresql://localhost:5050/security-db
spring.datasource.username=scrty
spring.datasource.password=scrty123
spring.jpa.hibernate.ddl-auto=update

I am trying to run my Spring Boot application inside a Docker container and I am also running a PostgreSQL database in another Docker container. However, my application cannot establish a connection with the PostgreSQL database.


Solution

  • The problem is, the containers are running in different networks and therefore can't communicate to each other. You can solve this problem by either putting your application also in your docker-compose.yaml as docker compose will create a network automatically and all the services join. For that, you can change your docker-compose.yaml like this:

    Solution 1:

    version: '3.8'
    services:
      app:
        build:
          context: .
          dockerfile: Dockerfile
        image: app:latest
      db:
        image: postgres
        restart: always
        container_name: security-db
        environment:
          POSTGRES_DB: security-db
          POSTGRES_USER: scrty
          POSTGRES_PASSWORD: scrty123
        ports:
          - '5050:5432'
    

    Like that, you don't need to expose port 5050 at all, if you don't want to access the database from your host. In app.image you can put whatever you want, this is your image name, which will be created and tagged when you execute docker compose up --build. app.build.context will specify the docker build context and app.build.dockerfile will specify your Dockerfile.

    Solution 2.

    You could also create a network manually with the following command:

    docker network create -d bridge my-bridge-network
    

    This will create a docker network called my-bridge-network. Now you have to connect both your container to this network. Execute the following command for both your containers (database and application)

    docker network connect <NETWORK> <CONTAINER>
    

    where you replace <NETWORK> with your created network name and <CONTAINER> with your container name.