Docker build cache in CI pipelines for faster builds
GitHub Actions cache, cache-from, cache-to, type=gha, BuildKit cache, cache-backend, registry cache, build time reduction
CI Builds Are Slow Without Caching
Every CI run starts from a fresh runner. Without cache, every layer rebuilds from scratch โ a 5-minute build on every push. GitHub Actions provides a cache backend that BuildKit can read and write between runs.
Enabling Cache in GitHub Actions
- name: Build and push with cache
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ghcr.io/${{ github.repository }}:${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=maxtype=gha uses GitHub Actions' native cache storage. mode=max caches all layers including intermediate ones, maximizing cache hits. On the first run the full build executes and populates the cache. Subsequent runs skip unchanged layers โ the dependency install layer is typically reused unless package.json changed.
Registry-Based Cache (Alternative)
cache-from: type=registry,ref=ghcr.io/org/app:buildcache
cache-to: type=registry,ref=ghcr.io/org/app:buildcache,mode=maxThis stores the cache as a special image tag in your registry โ useful when cache size exceeds GitHub's 10GB limit or when sharing cache across different CI systems.
