spring-bootdockermavendocker-composemicroservices

How to deal with a common Spring Boot module while Dockerizing micro-services application?


I would like to Dockerize all my Spring Boot micro services in a single docker-compose file. The problem is that all micro services are using a common module where I have written shared code (to avoid duplication) and I don't how to deal with it in the Docker process.

Here is the structure of the project :

root/
├── docker-compose.yml
├── common/
│   ├── pom.xml
│   └── src/
├── discovery/
│   ├── Dockerfile
│   ├── pom.xml
│   └── src/
├── gateway/
│   ├── Dockerfile
│   ├── pom.xml
│   └── src/
└── auth-service/
    ├── Dockerfile
    ├── pom.xml
    └── src/

docker-compose.yml (root) :

version: '3.8'

services:
  postgres:
    image: postgres:latest
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: postgres
    ports:
      - "5433:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - gym-tracker

  api-discovery:
    build:
      context: ./discovery
      dockerfile: Dockerfile
    networks:
      - gym-tracker

  api-gateway:
    build:
      context: ./gateway
      dockerfile: Dockerfile
    ports:
      - "8080:8080"
    depends_on:
      - api-discovery
    networks:
      - gym-tracker

  auth-service:
    build:
      context: .
      dockerfile: auth-service/Dockerfile
    depends_on:
      - postgres
      - api-discovery
      - api-gateway
    networks:
      - gym-tracker

networks:
  gym-tracker:
    external: true

volumes:
  postgres_data:
    driver: local

I tried a multi-staged approach with the following Dockerfile (auth-service) :

FROM maven:3.9.7-eclipse-temurin-21-alpine AS build
WORKDIR /app

COPY common/pom.xml /tmp/common/pom.xml
COPY common/src /tmp/common/src
RUN mvn -f /tmp/common/pom.xml clean install -DskipTests

COPY auth-service/pom.xml ./pom.xml
COPY auth-service/src ./src

RUN mvn clean package -DskipTests

FROM openjdk:21-jdk
WORKDIR /app

COPY --from=build /app/target/*.jar app.jar

EXPOSE 8082

ENTRYPOINT ["java", "-jar", "app.jar"]

I still got these errors while packaging the auth-service in the container :

15.57 [ERROR] COMPILATION ERROR : 
15.57 [INFO] -------------------------------------------------------------
15.57 [ERROR] /app/src/main/java/com/gym/tracker/authservice/controller/AuthController.java:[6,37] package com.gym.tracker.common.entity does not exist
15.57 [ERROR] /app/src/main/java/com/gym/tracker/authservice/controller/AuthController.java:[7,38] package com.gym.tracker.common.service does not exist
... and much more errors ...

How can I manage to resolve this issue properly please ?


Solution

  • You can try to use maven-assembly-plugin to include your common jar during parent pom build. Refer to this link below, if this solves your problem.

    https://gauthier-cassany.com/posts/build-jar-inside-docker