Skip to content

Instantly share code, notes, and snippets.

@gabrielbauman
Last active October 18, 2024 21:09
Show Gist options
  • Save gabrielbauman/b518981a730c7ff397a8140dc1204628 to your computer and use it in GitHub Desktop.
Save gabrielbauman/b518981a730c7ff397a8140dc1204628 to your computer and use it in GitHub Desktop.
Multi-stage docker build for Java/Maven apps
# Cache maven dependencies as an intermediate docker image
# (This only happens when pom.xml changes or you clear your docker image cache)
FROM maven:3-adoptopenjdk-15 as dependencies
COPY pom.xml /build/
WORKDIR /build/
RUN mvn --batch-mode dependency:go-offline dependency:resolve-plugins
# Build the app using Maven and the cached dependencies
# (This only happens when your source code changes or you clear your docker image cache)
# Should work offline, but https://issues.apache.org/jira/browse/MDEP-82
FROM maven:3-adoptopenjdk-15 as build
COPY --from=dependencies /root/.m2 /root/.m2
COPY pom.xml /build/
COPY src /build/src
WORKDIR /build/
RUN mvn -P dockerfile --batch-mode --fail-fast package
# Run the application (using the JRE, not the JDK)
# This assumes that your dependencies are packaged in application.jar
FROM adoptopenjdk:15-jre-hotspot as runtime
COPY --from=build /build/target/application.jar ./application.jar
EXPOSE 8080
CMD ["java", "-jar", "./application.jar"]
<project>
<profiles>
<profile>
<id>dockerfile</id>
<build>
<finalName>application</finalName>
</build>
</profile>
</profiles>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment