Maven builds in Docker

Occassionaly I need to do a build using a specific version of maven that is “pristine” - well, pristine-ish: I don’t want to download every single pom / jar file all over again.

I therefore have a little script that will run a dockerized version of maven for me, using the current working directory for the project to be build, and pointing to the local repository cache for maven.


if [ ! -f pom.xml ]; then
  echo "This is designed to run maven within docker in the current"
  echo "local project Make sure you have changed directories to"
  echo "the root of your local project"
  exit 1

docker run \
    -it \
    --rm \
    -v "$HOME/.m2":/root/.m2 \
    -v "$(pwd)":/usr/src/mymaven \
    -w /usr/src/mymaven \
    maven:3.5.0-jdk-8 \
    mvn clean compile verify


  • First six lines are just confirming that I am in a directory that might be a maven project
  • Then run within Docker:
    • use an interactive terminal (-it)
    • destroy the container on completion (-rm)
    • reuse any downloaded maven artifacts (-v "$HOME/.m2":/root/.m2)
    • use the current working directory as my build directory in the container (-v "$(pwd)":/usr/src/mymaven)
    • set the container’s working directory to that build directory (-w /usr/src/mymaven)
    • use container image maven version 3.5.0 with jdk 8 (maven:3.5.0-jdk-8)
    • run the maven commands I usually want (mvn clean compile verify)

If you are playing with this, it is the last two you are most likely to want to change - what combination of maven and jdk do you want and/or what maven commands do you want to run.