Caching Maven dependencies in a Docker build

What I learned today — 18 June 2018

Multi-stage Docker builds are a great way to ensure your builds are 100% reproducible AND as lean as possible. On the downside a Maven build in Docker may have to download many dependencies each time it runs. Fortunately this can be mitigated by Docker caching and the Maven Dependency Plugin. To take advantage of this start by COPY’ing the pom.xml file and RUN’ing the dependency:go-offline goal. This will download most* of the dependencies required for the build and cache them for as long as the pom.xmldoesn’t change. Next, perform the necessary build of your source code and lastly copy the artefact into a run image. Here is an example Dockerfile demonstrating all of the above:

# Step : Test and package
FROM maven:3.5.3-jdk-8-alpine as target
WORKDIR /build
COPY pom.xml .
RUN mvn dependency:go-offline

COPY src/ /build/src/
RUN
mvn package

# Step : Package image
FROM openjdk:8-jre-alpine
EXPOSE 4567
CMD exec java $JAVA_OPTS -jar /app/my-app.jar
COPY --from=target /build/target/*jar-with-dependencies.jar /app/my-app.jar