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 mvn install
2. docker build with secret
I assume your settings.xml located in
docker buildx build --secret id=maven_settings,src="$HOME/.m2/settings.xml" -t tmp -f Dockerfile .
Two key points here:
- Enable buildkit by replace
docker buildx build. Or you can do this by exporting env. variable
DOCKER_BUILDKIT=1 docker build ...
- Define maven_settings secret by