Caching Jar dependencies for Maven-based Docker builds

I’m building a Docker image from this Dockerfile:

FROM maven:3.3.3-jdk-8
MAINTAINER Mickael BARON  

ADD pom.xml /work/pom.xml
WORKDIR /work
RUN mvn dependency:go-offline --fail-never

ADD ["src", "/work/src"]
RUN ["mvn", "package"]

With this Dockerfile, I force to download the dependencies before packaging my Java project. Thus, I don’t have to redownload the dependencies every time I changed a file from my src directory.

  • Expose container port to Host using Docker for Windows in Windows 10
  • Jenkins,Sonar in single docker container
  • NGINX + PHP-FPM - Should I keep them in separate containers or not?
  • Configuring bitbucket pipelines with Docker to connect to AWS
  • enable CORS in docker for rails apps rest-client
  • Docker “Operation not permitted” issue on Windows
  • But, there is a problem and this problem is depending on the version of Maven (base image). In fact, the dependencies are downloaded but they are not persisted into the ~/.m2 directory of the container. It’s empty. Thus, when I change some source file all the dependencies are redownloaded.

    However, I noticed that if I change the version of Maven from the base image (for example FROM maven:3.2.5-jdk-8), it works.

    Very strange, isn’t it?

  • Is Docker a replacement for git source control? [closed]
  • Error using Poseidon: Poseidon::Errors::UnableToFetchMetadata
  • Docker - any way to give access to host USB or serial device?
  • Allowing custom scp/sftp/rsync in sandbox shell
  • Docker Ubuntu 12.04
  • Relative path with zip in vrt file (vsizip)?
  • 2 Solutions collect form web for “Caching Jar dependencies for Maven-based Docker builds”

    I’m afraid it’s because of this VOLUME instruction they’ve added:

    https://github.com/carlossg/docker-maven/blame/8ab542b907e69c5269942bcc0915d8dffcc7e9fa/jdk-8/Dockerfile#L11

    It makes /root/.m2 a volume and thus any changes to that folder made by build steps are not brought on to the following build containers.

    There is a new instruction regarding this topic:
    https://github.com/carlossg/docker-maven#packaging-a-local-repository-with-the-image

    The $MAVEN_CONFIG dir (default to /root/.m2) is configured as a volume so anything copied there in a Dockerfile at build time is lost. For that the dir /usr/share/maven/ref/ is created, and anything in there will be copied on container startup to $MAVEN_CONFIG.

    To create a pre-packaged repository, create a pom.xml with the dependencies you need and use this in your Dockerfile. /usr/share/maven/ref/settings-docker.xml is a settings file that changes the local repository to /usr/share/maven/ref/repository, but you can use your own settings file as long as it uses /usr/share/maven/ref/repository as local repo.

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.