Search code examples
postgresqldockerdocker-composedockerfilemicronaut

Docker compose with micronaut trying to connect to postgres in localhost


I have a micronaut app that I'm trying to put in a docker container and have it connect to another docker container that has a postgres image. I think I followed the procedure to tell it to connect to postgres in another container but no, when I try to run my docker image it fails because it can't connect to postgres on localhost:5432. Even though:

Dockerfile:

FROM openjdk:14
COPY target/time-*.jar time.jar
EXPOSE 8080
CMD ["java", "-Dmicronaut.environments=docker", "-Dcom.sun.management.jmxremote", "-Xmx128m", "-jar", "time.jar"]

I told it to run with my docker profile.

My application-docker.yml looks like this:

micronaut:
  application:
    name: time
  server:
    netty:
      access-logger:
        enabled: true
        logger-name: access-logger

datasources:
  default:
    url: jdbc:postgresql://db:5432/postgres
    driverClassName: org.postgresql.Driver
    username: postgres
    password: postgres
    schema-generate: CREATE_DROP
    dialect: POSTGRES
    schema: time
jpa.default.properties.hibernate.hbm2ddl.auto: update

flyway:
  datasources:
    default:
      enabled: true
      schemas: time
...

When I ran my web container it says it's running with the docker profile but fails to connect to localhost! Why??

18:41:57.947 [main] INFO  i.m.context.env.DefaultEnvironment - Established active environments: [docker]
18:41:58.625 [main] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
18:41:59.656 [main] ERROR com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Exception during pool initialization.
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.

This is my docker-compose.yml:

version: "3.3"
services:
  web:
    image: time
    build: .
    ports:
      - "8080:8080"
    depends_on:
      - db
    links:
      - db
    environment:
      JDBC_URL: jdbc:postgresql://db:5432/time
      JDBC_HOST: db
      JDBC_PORT: 5432

  db:
    image: "postgres"
    ports:
      - "5432"
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres

What am I missing?


Solution

  • It was trying localhost because my application-docker.yml wasn't in the jar. Someone here helped me out: Micronaut not connecting to db in yml