Combine go-offline goal of maven-dependency-plugin
, maven's offline mode with docker multistage builds.
A reference Dockerfile
could be :
# Step : Test and package
FROM maven:3.5.3-jdk-8-alpine as builder
WORKDIR /build
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src/ /build/src/
# -o flag will instruct maven to build on offline mode
RUN mvn -o package
# Step : Package image
FROM openjdk:8-jre-alpine
EXPOSE 4567
CMD exec java $JAVA_OPTS -jar /app/my-app.jar
COPY --from=builder /build/target/*jar-with-dependencies.jar /app/my-app.jar
Invoking dependency:go-offline
will fetch required artifacts on container's local repository. Thanks to docker layer caching, this step will be cached so it will be skipped in a new build attempt.
An important note is that copying pom.xml
should precede source code copying as a change on pom.xml
must trigger a new pull of maven artifacts as project's dependencies may have changed.
Reference
EDIT: Note that depending on your pom.xml
, you may face an open Maven Dependency plugin issue on which some dependencies are not fetched from go-offline
goal as they should, resulting in build failure. As a workaround, you can try Romain's answer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…