Skip to content

Instantly share code, notes, and snippets.

@Mahoney
Last active February 28, 2020 20:34
Show Gist options
  • Save Mahoney/85e8549892e0ae5bb86ce85339db1a71 to your computer and use it in GitHub Desktop.
Save Mahoney/85e8549892e0ae5bb86ce85339db1a71 to your computer and use it in GitHub Desktop.
An example maintaining a cache in an image
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
function clear_build_cache {
docker builder prune --filter type=exec.cachemount -f > /dev/null
}
function clean_start {
rm -f appended.txt
rm -f Dockerfile
docker image rm -f prev:latest > /dev/null
clear_build_cache
}
function create_docker_file {
# shellcheck disable=SC2016
echo \
'# syntax=docker/dockerfile:experimental
FROM bash
ARG TO_APPEND=1
RUN mkdir /output_dir
RUN --mount=type=cache,target=/cached_dir \
touch /cached_dir/appended.txt && \
echo $TO_APPEND >> /cached_dir/appended.txt && \
cp /cached_dir/appended.txt /output_dir/appended.txt
' > ./Dockerfile
}
function first_docker_build_no_cache_from {
local to_append=$1
export DOCKER_BUILDKIT=1
docker build \
. \
-t prev:latest \
--build-arg BUILDKIT_INLINE_CACHE=1 \
--build-arg TO_APPEND="$to_append"
}
function docker_build {
local to_append=$1
export DOCKER_BUILDKIT=1
docker build \
. \
-t prev:latest \
--cache-from prev:latest \
--build-arg BUILDKIT_INLINE_CACHE=1 \
--build-arg TO_APPEND="$to_append"
}
function assert_results {
local expected=$1
local id
id=$(docker create prev:latest)
docker cp "$id":/output_dir/appended.txt appended.txt
docker rm -v "$id" > /dev/null
results=$(cat appended.txt)
echo "$results"
total_lines="$(wc -l < appended.txt | tr -d ' ')"
if [[ "$total_lines" != "$expected" ]]; then
>&2 echo "Expected $expected lines, got $total_lines!"
exit 1;
fi
}
function main {
clean_start
create_docker_file
first_docker_build_no_cache_from "$(date)"
docker_build "$(date)"
echo "After 2 runs, no buildkit cache clear, there should be 2 lines in the file"
assert_results 2
clear_build_cache
docker_build "$(date)"
echo "After a buildkit cache clear & a further run there should be 3 lines in the file because the previous state should have come from the image cache"
assert_results 3
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment