Optimizing Docker Images Using Directory Caching

Share the page with

Directory caching

The BuildKit plugin provides the option for directory caching, which is an incredibly useful tool for speeding up build times without saving a lot of files that are unnecessary for the runtime into your image. It allows us to save the contents of a directory inside the image in a special layer that can be bind-mounted at build time and then unmounted before the image snapshot is made. This is often used to handle directories where tools like Linux software installers (apt, apk, dnf, etc.), and language dependency managers (npm, bundler, pip, etc.), download their databases and archive files.

The docker file is given below:

# syntax=docker/dockerfile:1
FROM ubuntu:22.04 as system_builder
USER root
RUN --mount=type=cache,target=/root/.cache apt-get update && \
apt-get install -y --no-install-recommends gfortran gcc libomp-dev curl git \
python3 python3-pip cmake ninja-build \
liblapack-dev libopenblas-dev libhdf5-dev \
libplplot-dev plplot-driver-cairo libboost-all-dev \
gnuplot doxygen libgtk-4-dev && apt-get clean

FROM system_builder
ENV EASIFEM_BUILD_DIR /easifem/build
ENV EASIFEM_SOURCE_DIR /easifem/src
ENV EASIFEM_INSTALL_DIR /easifem/install
ENV EASIFEM_TEST_DIR /easifem/tests

COPY ./tests/* $EASIFEM_TEST_DIR/

WORKDIR $EASIFEM_TEST_DIR

RUN gfortran -o main.out main.F90 && ./main.out

By using

RUN --mount=type=cache,target=/root/.cache apt-get update && \

we tell BuildKit to mount a caching layer into the container at /root/.cache for the duration of this build step. In this way, we remove the contents of .cache directory from the resulting image, and it will be remounted and available to apt-get in consecutive builds.

Share the page with