iTranslated by AI
Mastering Docker Caching to the Fullest
tl;dr
- Download dependency packages first
- Remember that multi-stage builds are essential
- Use
RUN --mount=type=cache(but check if you can use BuildKit!) - High expectations for
pnpm fetchas well
Introduction
Have you ever spent what felt like forever waiting for dependency packages to download while developing with Docker? Many of you might be compromising, thinking, "Adding dependencies doesn't happen that often, I'll just bear with it..."
Doesn't happen often? Are you sure?
Even if you aren't adding them, dependency updates happen frequently, and you might update the base image too. Re-downloading everything every single time is unbearable. If you're on a mobile connection, your data cap will vanish in an instant!
So, in this article, I explored ways to leverage caching to prevent repeated downloads of dependency packages.
Method
Method 1. Writing a Dockerfile without much thought
First, as a starting point, let's write a Dockerfile without overthinking it. We'll use a React application as an example.
npx create-react-app myapp
Next, we'll create a Dockerfile to build this React application. Here, we utilize multi-stage builds to place the application built with node onto nginx. If you aren't considering caching, it would look something like this.
FROM node:16 AS builder
WORKDIR /workspace
# Copy only files related to the build so that the hash value changes as little as possible.
COPY package.json package-lock.json ./
COPY public public
COPY src src
RUN npm install
RUN npm run build
FROM nginx:stable
COPY --from=builder /workspace/build /usr/share/nginx/html
Let's try building this twice in a row.
docker build --progress=plain -t localhost/myapp:latest .
In the second log, npm install shows CACHED, indicating that the layer cache was used. Of course, this step finishes instantly.
#12 [builder 6/7] RUN npm install
#12 sha256:b8677258444adb8833e63e5b338e22cd569bf6a6e4fd5120f94873af48fc058e
#12 CACHED
Now that we know the cache is working, let's change the code slightly and build again.
#12 [builder 6/7] RUN npm install
#12 sha256:3575b466596b16098e185319b3ff5472a0163b1e89c520132a214019cd20b47a
(omitted)
#12 DONE 234.2s
Two... two hundred and thirty-four seconds...
Come to think of it, I recall hearing news about traffic being congested due to heavy snow. It must be because of that.
Of course, it wasn't the snow's fault; it's because changing src/App.js altered the hash value of the layer executing npm install. This causes dependency packages to be re-downloaded every time the source code is modified.
Method 2. Install dependency packages first
How can we prevent the download of dependency packages even when the source code is modified?
A common method is to COPY the files listing dependencies first and complete only the installation beforehand. For npm, installed packages are listed in package.json and package-lock.json. Let's COPY these and execute npm install immediately.
FROM node:16 AS builder
WORKDIR /workspace
# Execute only npm install first.
COPY package.json package-lock.json ./
RUN npm install
COPY public public
COPY src src
RUN npm run build
FROM nginx:stable
COPY --from=builder /workspace/build /usr/share/nginx/html
Just like Method 1, let's try: build → code change → build.
#10 [builder 4/7] RUN npm install
#10 sha256:bcd99585d52f56e16d250aad7fcf7f66cebb1aa1b45fe4da6ed44bfaaf7da65f
#10 CACHED
(omitted)
#13 [builder 7/7] RUN npm run build
#13 sha256:f76e83bb9755ce32925e9b302c7b14c2509a4b3cc78b3841cda79c144c7c0c40
(omitted)
#13 DONE 32.0s
Success! npm install is properly cached! Since the source code changes don't matter at the point where npm install is executed, the cache is used.
By the way, back in the days before multi-stage builds, it was common to combine all commands into a single RUN like RUN command1 && command2 && ..., but now it is standard practice to separate them in stages other than the final one. This is also to maximize the benefits of caching. In this example, we are switching from a node image to an nginx image, but even if the runtime image were node, multi-stage builds should be considered essential now.
Now, let's change the author in package.json and build one more time just in case[1]...
#10 [builder 4/7] RUN npm install
#10 sha256:fcb3324fa550e83d308b200f83db0bd7051983aca78b6418b49a603bf815da82
(omitted)
#10 DONE 128.3s
I knew it.
Even if it is not affected by source code changes, if you change package.json, the layer's hash value changes.
You say you don't change package.json that often? Don't you have things like eslintConfig or browserslist in your package.json? Is the version always the same? Don't you ever add, remove, or upgrade dependency packages? It is painful to re-download every package every time that happens.
Method 3. Using --mount=type=cache
This is the real deal.
BuildKit, which is used for building images, includes a syntax called RUN --mount=.... This feature allows you to mount a specific directory during the execution of RUN.
Incredibly, this includes a function to specify a cache directory using RUN --mount=type=cache. The specified directory can persist data across builds. Furthermore, the files within that directory are not included in the image layers.
Since npm uses /root/.npm as its cache directory, specifying this directory ensures that even if package.json is updated, it shouldn't need to re-fetch tarballs that are already cached.
# syntax=docker/dockerfile:1
FROM node:16 AS builder
WORKDIR /workspace
COPY package.json package-lock.json ./
# Cache /root/.npm
RUN --mount=type=cache,target=/root/.npm npm install
COPY public public
COPY src src
RUN npm run build
FROM nginx:stable
COPY --from=builder /workspace/build /usr/share/nginx/html
If we build again after changing the author in package.json, just like in Method 2:
#14 [builder 4/7] RUN --mount=type=cache,target=/root/.npm npm install
#14 sha256:84029e3950b71f66b6565a5937851cdcbfc9a3f6948b8fd7840560bb562468fe
(omitted)
#14 DONE 34.2s
Since the layer's hash value changes, the command itself won't be cached, but the execution of npm install is significantly improved to 34.2 seconds. This is because the npm cache is being used for previously downloaded packages. With this, even if you add or update packages, you only need to download that specific portion, meaning you'll never have to download every single package from scratch again.
Hurray!
Supplementary Note 1. Couldn't we just cache node_modules?
While caching /workspace/node_modules is faster, if you use it for production, you might run npm install --production and remove devDependencies. In that case, you would have to start over from the download step for those packages, which is why I specified /root/.npm instead.
Since you can specify multiple --mount=... options, caching both might also be a good idea.
RUN \
--mount=type=cache,target=/root/.npm \
--mount=type=cache,target=/workspace/node_modules \
npm install
Supplementary Note 2. What about Yarn or pnpm?
For Yarn and pnpm, the package lock files are yarn.lock and pnpm-lock.yaml, and the cache directories are /usr/local/share/.cache/yarn/v6 and /root/.pnpm-store, respectively.
Substituting these paths should work in the same way.
pnpm also has an experimental command, pnpm fetch, which downloads packages using only the pnpm-lock.yaml file. This makes your build even more resilient to changes in package.json. Note that pnpm is not included in the official node images by default.
Supplementary Note 3. For APT or yum
While I've used npm as an example so far, there are times you'll want to add packages via APT or yum. RUN --mount=type=cache is great for those cases too.
In the past, you likely ran apt-get clean or rm -rf ... at the end to clear the cache for runtime packages. With cache mounts, that's no longer necessary.
For APT:
FROM ubuntu:20.04
RUN \
--mount=type=cache,target=/var/lib/apt/lists \
--mount=type=cache,target=/var/cache/apt/archives \
apt-get update \
&& apt-get install -y --no-install-recommends build-essential
For yum:
FROM centos:7
RUN --mount=type=cache,target=/var/cache/yum \
yum groupinstall -y 'Development Tools' \
&& yum install -y kernel-devel kernel-headers
Supplementary Note 4. I can't use BuildKit...
You might not be able to use BuildKit for various reasons:
- "The Docker version we use is fixed to an older version before BuildKit."
- "The CI/CD environment doesn't support BuildKit."
- "I'm using Podman[2]"
In such cases, either try your best to enable BuildKit or settle for "Method 2" (Wait, are we settling again?).
Summary
What did you think?
While you need to check if BuildKit is available for professional use, RUN --mount=... is incredibly useful. There are other types besides type=cache, such as type=bind, type=secret, and type=tmpfs, so it might be interesting to explore them.
Even if you can't use BuildKit, please download your packages first. And multi-stage builds are essential.
Also, while this article focused solely on caching, it's also quite important to use .dockerignore to prevent unnecessary files from being sent to the Docker daemon. After all, node_modules is heavier than a black hole.
-
Of course, you don't actually need to build "just in case." ↩︎
-
While there are ways to use BuildKit with Podman, it's honestly a bit of a hassle. ↩︎
Discussion
tldrの
「RUN --mount=cache=type を使おう」は、正しくは「RUN --mount=type=cache を使おう」だと思います。
ほんとですね.
全然気づいてませんでした…