title: How to build a maven project in a docker container efficiently?
body: <p>I am trying to improve the build process by reducing it's duration. The build is done in a docker container based on the <a href="https://hub.docker.com/_/maven?tab=description" rel="nofollow noreferrer">official maven docker image</a>.   </p>
  
  <p>The way I am doing it right now works well, but doesn't preserve the local maven repository for subsequent builds, which means that all downloads need to happen again for every build.</p>
  
  <p>Let's focus on what I actually tried to improve that.
  I tried the following steps:
  1. create a docker volume for maven's .m2 directory
  2. build a custom maven image (contains custom maven settings)
  3. run a docker container based on that image, mounting the volume from step 1 and bind mount the maven project (the directory that contains the top level pom-file)</p>
  
  <p>Here is the dockerfile for the custom maven docker image:</p>
  
  <pre><code>FROM maven:3.6.1-jdk-11
  
  # Use custom settings file for maven
  COPY my-settings.xml /usr/share/maven/conf/settings.xml
  
  CMD ["/bin/bash"]
  </code></pre>
  
  <p>Here is the bash script that does the rest</p>
  
  <pre class="lang-sh prettyprint-override"><code># Provide basis for Maven local repository reuse
  docker volume create --name maven-repo
  
  # Build maven docker image with custom settings.xml
  docker build --file "${WORKSPACE}"/tools/maven/Dockerfile \
               --tag my-maven-image:latest \
               "${WORKSPACE}"/tools/maven/
  
  # Build using maven in the container
  # The options -it are just there for debug purposes
  docker run -it \
          --mount source=maven-repo,destination=/root/.m2 \
          --mount type=bind,source="${WORKSPACE}"/my-maven-project,destination=/usr/src/my-maven-project \
          --name maven-container my-maven-image:latest \
          --workdir /usr/src/my-maven-project
          mvn clean install
  </code></pre>
  
  <p>I expect the that <code>mvn clean install</code> is run in the <code>/usr/src/my-maven-project</code> directory of the container. Instead this directory can't be found.</p>
  
  <p>I also plan to get rid of the interactive mode of the <code>docker run</code> command as soon as it works, I assume the logs of the maven command can be found in the logs of the docker container.</p>
  
  <p>After a successful build I assume the artifacts will be in the same directories as if I had run the maven command from the docker host machine.</p>