Bind .m2 file to docker on build stage

Viewed 2723

I tried build a spring boot project in docker container based on below docker file.But every times all mvn dependency download from internet. How can I bind local .m2 file when i build the docker file.

This is my Dockerfile

FROM maven:3.5-jdk-8-alpine AS build 
COPY /src /usr/src/javaspring/src
COPY pom.xml /usr/src/javaspring
COPY Dockerfile /usr/src/javaspring
RUN mvn -f /usr/src/javaspring/pom.xml clean install


FROM openjdk:8-jre-alpine
COPY --from=build /usr/src/javaspring/target/javaspring-1.0.jar app.jar
ENTRYPOINT [“java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
2 Answers

You should mount the content of your project into the docker image and the $HOME/.m2/ into the image instead of copying everything into the image and building a new image..

The $PWD is the local directory where your pom.xml file is located and the src directory exists...

docker run -it --rm \
  -v "$PWD":/usr/src/mymaven \ (1)
  -v "$HOME/.m2":/root/.m2 \ (2)
  -v "$PWD/target:/usr/src/mymaven/target" \ (3)
  -w /usr/src/mymaven \ (4)
  maven:3.5-jdk-8-alpine \ (5)
  mvn clean package
  1. defines the location of your working directory where pom.xml is located.
  2. defines the location where you have located your local cache.
  3. defines the target directory to map it into the image under the given path
  4. defines the working directory.
  5. defines the name of the image to be used.

So you don't need to create an new image to build your stuff with Maven. Simply run an existing image via the following command:

docker run -it --rm \
  -v "$PWD":/usr/src/mymaven \
  -v "$HOME/.m2":/root/.m2 \
  -v "$PWD/target:/usr/src/mymaven/target" \ 
  -w /usr/src/mymaven \
  maven:3.5-jdk-8-alpine mvn clean package

Since Docker Engine 18.09, there is a new set of build enhancements and one of them is "Cache Mounts". It will not let you mount your local .m2 - it addresses the need for caching dependencies in a different way. To use it specify --mount option to your RUN command:

# Dockerfile
FROM maven:3.8.3-jdk-11 AS maven-builder
...
RUN --mount=type=cache,id=m2-cache,sharing=shared,target=/root/.m2  \
  mvn --file /xyz/pom.xml package

More: https://github.com/moby/buildkit/blob/master/frontend/dockerfile/docs/syntax.md

Related