spring-bootdockermavendockerfile

Running maven commands in Docker file and create Docker image


I need to create a Docker image from a Docker file to Dockerize my Spring Boot application. But I want to generate the JAR file from inside the Docker file, not by executing the mvn clean package by user. I tried the code below, but it does not generate the JAR file:

FROM openjdk:17-jdk-slim
COPY pom.xml pom.xml
COPY src src
RUN mvn clean package
COPY ./target/my-app.jar my-app.jar
ENTRYPOINT ["java","-jar","/my-app.jar"]

Solution

  • To build your Spring Boot application and generate the JAR file within the Dockerfile, it's recommended to use a multi-stage build. This approach allows you to compile your application in one stage and run it in another, resulting in a smaller and more efficient Docker image. Here's how you can structure your Dockerfile:

    # Stage 1: Build the application
    FROM maven:3.8.5-openjdk-17 AS builder
    WORKDIR /app
    COPY pom.xml .
    COPY src ./src
    RUN mvn clean package -DskipTests
    
    # Stage 2: Run the application
    FROM openjdk:17-jdk-slim
    WORKDIR /app
    COPY --from=builder /app/target/*.jar app.jar
    ENTRYPOINT ["java", "-jar", "app.jar"]
    

    Explanation:

    1. Builder Stage:

      • Uses the Maven image with OpenJDK 17.
      • Sets the working directory to /app.
      • Copies the pom.xml and src directory into the container.
      • Runs mvn clean package to build the application and generate the JAR file.
    2. Runtime Stage:

      • Uses a slim OpenJDK 17 image for a smaller footprint.
      • Sets the working directory to /app.
      • Copies the JAR file from the builder stage.
      • Specifies the entry point to run the application.

    This method ensures that your final Docker image contains only the necessary runtime dependencies, keeping it lightweight and efficient.