IMLC.ME

How to mount Maven settings.xml in Docker build

In an early version, Docker does not support mount external files into docker build process. It's really embarrassing when we build Java project. Because we need the Maven settings.xml where we store the internal repository, auth credentials. I saw some practises like injects username, password, repo mirror or mirror address via build arguments. Or copy the settings.xml into every projects and COPY into build context.

Latest Docker introduced build secrets in its buildkit feature. With this feature, we can achieve same requirement more smoothly.

1. RUN maven with secret

Firstly, you need "--mount=type=secret" in your RUN command. In below example, it requires Docker to mount a secret which id is maven_settings, and mount the secret as a file in location "/root/.m2/settings.xml".

Of course, you can change the destination path. Using root account is usually not a good idea.

RUN --mount=type=secret,id=maven_settings,dst=/root/.m2/settings.xml mvn install

2. docker build with secret

I assume your settings.xml located in $HOME/.m2/settings.xml:

docker buildx build --secret id=maven_settings,src="$HOME/.m2/settings.xml" -t tmp -f Dockerfile .

Two key points here:

  1. Enable buildkit by replace docker build to docker buildx build. Or you can do this by exporting env. variable DOCKER_BUILDKIT=1 docker build ...
  2. Define maven_settings secret by --secret id=maven_settings,src="$HOME/.m2/settings.xml"

References

docker build reference - docker docs
Dockerfile reference - docker docs