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"]
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"]
Builder Stage:
Runtime Stage:
This method ensures that your final Docker image contains only the necessary runtime dependencies, keeping it lightweight and efficient.