Connecting postgre to tomcat application with docker-compose

I am new to docker and my niexperince is getting me confused here. I have built a docker compose for my projet that contains postgres database on a tomcat java application. But the as much as the application is working ok, there is no connection to the database. the following is my docker-compose. Can anyone please show and guide me in the right direction. I am currently running this application on my local ubuntu system.

name: 'klarys'

services:
  kla_home_api:
    image: tomcat:10.0.16-jdk8-ubuntu22-klarysapi
    container_name: kla_home_api
    build: ./api.klarys.com
    ports:
      - "4080:8080"
    environment:
      DB_URL: "jdbc:postgresql://kla_home_db:5432/klarys_database"
      DB_USER: "klarys_database"
      DB_PASS: "klarys_pass"
    restart: on-failure
    depends_on:
      kla_home_db:
        condition: service_healthy
    networks:
      - klanet

  kla_home_db:
    image: postgres:16 
    container_name: kla_home_db 
    restart: always
    shm_size: 128mb
    environment:
      - POSTGRES_PASSWORD=klarys_pass
      - POSTGRES_USER=klarys_database
      - POSTGRES_DB=klarys_database
    ports:
      - 5432:5432
    volumes:
      - pgdata:/var/lib/postgresql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 10s
      retries: 5
      start_period: 30s
      timeout: 10s
    networks:
      - klanet

  kla_home_adminer:
    image: adminer
    container_name: klarys_adminer
    restart: always
    ports:
      - 4040:8080
    networks:
      - klanet

volumes:
  pgdata:

networks:
  klanet:

And most importantly how it would communicate with the jdbc url (url=“jdbc:postgresql://localhost:5432/klarys_database”)

Your config seems correct on first sight. You create a Docker network, attach all containers to it, reference the DB by its Docker service name, which will be resolved by Docker DNS.

Check with docker ps the status of your services, as DB has a healthcheck and app uses depends_on.

You usually don’t use localhost in Docker, as that is only 127.0.0.1 within the container, you usually can’t connect to host or other containers with it.