Skip to content

Instantly share code, notes, and snippets.

@hholst80
Created July 16, 2022 16:10
Show Gist options
  • Save hholst80/f6ded6280855c9dcb54f75c032821bfc to your computer and use it in GitHub Desktop.
Save hholst80/f6ded6280855c9dcb54f75c032821bfc to your computer and use it in GitHub Desktop.
# This is how we usually do things.
FROM alpine:latest AS t1
RUN <<EOF
find /var/cache/apk
apk add --no-cache build-base
find /var/cache/apk
EOF
# This won't actually do anything. Cache needs to be enabled.
# OK to be fair it does cache some meta data. Mostly useless
# to cache that becaues it's like 3 MB in size.
FROM alpine:latest AS t2
RUN <<EOF
find /var/cache/apk
apk add build-base
find /var/cache/apk
EOF
# This will use a cache. But it does the opposite of what we want.
# It always downloads the artifacts; and it stores them in the image!
FROM alpine:latest AS t3
RUN <<EOF
ln -s /var/cache/apk /etc/apk/cache
find /var/cache/apk
apk add build-base
find /var/cache/apk
EOF
# At first, this looks bad. But look at the size, the cache will not be baked
# into the image. The cache is only mounted during build and not kept in the
# final image.
#
# ❯ docker images | egrep '^t[1234]'
# t4 latest b7aa44fd860c 9 seconds ago 190MB
# t3 latest 9bcc3c4829ec 21 seconds ago 257MB
# t2 latest 0a674420af3e 34 seconds ago 193MB
# t1 latest 5cb337865a72 46 seconds ago 190MB
FROM alpine:latest AS t4
RUN --mount=type=cache,target=/var/cache/apk <<EOF
ln -s /var/cache/apk /etc/apk/cache
find /var/cache/apk
apk add build-base
find /var/cache/apk
EOF
@hholst80
Copy link
Author

hholst80 commented Jul 16, 2022

The point here is that you can update your Dockerfile and change the package deps. The cache will still survive. Across all builds not just the same Dockerfile. That will save you quite a bit of download if you have a dedicated build machine for your CI/CD pipelines. More importantly, if you are building on your laptop and you're on a 3G connection this becomes absolutely a must. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment