Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mounting Volume as part of a multi-stage build

How can I mount a volume to store my .m2 repo so I don't have to download the internet on every build?

My build is a Multi stage build:

FROM maven:3.5-jdk-8 as BUILD

COPY . /usr/src/app
RUN mvn --batch-mode -f /usr/src/app/pom.xml clean package

FROM openjdk:8-jdk
COPY --from=BUILD /usr/src/app/target /opt/target
WORKDIR /opt/target

CMD ["/bin/bash", "-c", "find -type f -name '*.jar' | xargs java -jar"]
like image 301
DarVar Avatar asked Jul 05 '18 15:07

DarVar


People also ask

Are docker volumes available during build?

Although there's no functionality in Docker to have volumes at build-time, you can use multi-stage builds, benefit from Docker caching and save time by copying data from other images - be it multi-stage or tagged ones.

What is the advantage of multi-stage builds?

Multistage builds let the developer automate the creation process of applications that require some amount of compilation. Developers can create versions that target different OS versions or any other process dependency, which is a big benefit of the approach.

How do docker multistage builds work?

A multistage build allows you to use multiple images to build a final product. In a multistage build, you have a single Dockerfile, but can define multiple images inside it to help build the final image.

Can we have multiple Dockerfiles?

Let's say we have two Dockerfiles, one for building the backend and another for building the frontend. We can name them appropriately and invoke the build command two times, each time passing the name of one of the Dockerfiles: $ docker build -f Dockerfile.


1 Answers

You can do that with Docker >18.09 and BuildKit. You need to enable BuildKit:

export DOCKER_BUILDKIT=1

Then you need to enable experimental dockerfile frontend features, by adding as first line do Dockerfile:

# syntax=docker/dockerfile:experimental

Afterwards you can call the RUN command with cache mount. Cache mounts stay persistent during builds:

RUN --mount=type=cache,target=/root/.m2 \
    mvn --batch-mode -f /usr/src/app/pom.xml clean package
like image 109
Marek Obuchowicz Avatar answered Oct 01 '22 02:10

Marek Obuchowicz