How to use Docker layer caching in GitHub Actions
BuildKit cache, cache-from, cache-to, gha cache type, registry cache, layer cache hit, cache invalidation, build speed optimization
Why Docker Builds Are Slow
Docker builds images layer by layer. If a layer's inputs change, that layer and all layers below it must be rebuilt. Without caching, every CI run rebuilds all layers including slow steps like apt-get install.
GitHub Actions Cache Backend
- uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ghcr.io/${{ github.repository }}:latest
cache-from: type=gha
cache-to: type=gha,mode=maxtype=gha uses the GitHub Actions cache backend (the same one as actions/cache) to store Docker layer data. cache-from reads from the cache. cache-to writes to it after a successful build. mode=max caches all layers including intermediate ones — mode=min only caches the final image layers.
Registry Cache (Alternative)
For private repositories with large images, using a registry as the cache backend is more efficient:
cache-from: type=registry,ref=ghcr.io/${{ github.repository }}:cache
cache-to: type=registry,ref=ghcr.io/${{ github.repository }}:cache,mode=maxThis stores cache data as a manifest in your container registry, surviving beyond GitHub's 7-day cache eviction window.
