Cache a public Docker image in a GitHub Action
Here’s a reusable GitHub Action definition that caches a public Docker image:
---
name: Docker public image cache
description: Pull and cache a public Docker image for reuse
inputs:
image_name_tag:
description: Docker image name and tag to pull and cache
required: true
runs:
using: "composite"
steps:
- name: Restore image cache
id: restore_cache
uses: actions/cache@v4
with:
path: 'ci/cache/docker'
key: 'cache-docker-${{ inputs.image_name_tag }}'
- name: Update image cache on cache miss
if: steps.restore_cache.outputs.cache-hit != 'true'
shell: bash
run: >
docker pull '${{ inputs.image_name_tag }}'
&& mkdir -p $(dirname './ci/cache/docker/${{ inputs.image_name_tag }}.tar')
&& docker image save '${{ inputs.image_name_tag }}' --output './ci/cache/docker/${{ inputs.image_name_tag }}.tar'
- name: Use image cache on cache hit
if: steps.restore_cache.outputs.cache-hit == 'true'
shell: bash
run: >
docker image load --input './ci/cache/docker/${{ inputs.image_name_tag }}.tar'
If you have this action definition at .github/actions/docker_image_cache
in the repo, then you can use it from a workflow like this:
---
jobs:
foo_job:
runs-on: ubuntu-latest
steps:
- name: LocalStack public image cache
uses: ./.github/actions/docker_image_cache
with:
image_name_tag: 'localstack/localstack:4.2.0'
After the first run, you should see output like this from the action, showing that it has loaded the Docker image from the cache:
Cache hit for: cache-docker-localstack/localstack:4.2.0
Received 167772160 of 591491524 (28.4%), 160.0 MBs/sec
Received 348127232 of 591491524 (58.9%), 165.6 MBs/sec
Received 536870912 of 591491524 (90.8%), 166.3 MBs/sec
Received 591491524 of 591491524 (100.0%), 167.5 MBs/sec
Cache Size: ~564 MB (591491524 B)
Note that it does still take several seconds to load that much data from the GitHub Actions cache, but it is still significantly faster than fetching it over the internet.