โAdd GitHub Actions caching to my Docker build using cache-from and cache-to of type gha so unchanged layers are reused. Explain how layer caching saves time.โ
07 โ Speed up builds with caching
Category: Optimization ยท Priority: Medium ยท Step: 8
Cache npm dependencies and Docker layers so repeat runs take seconds, not minutes.
๐ฏ What is this task?
CI re-downloads and rebuilds everything on a clean machine each time โ which is slow. Caching stores expensive results between runs. You'll cache two things: npm packages (already easy via setup-node) and Docker build layers (via GitHub Actions cache).
๐ค AI Prompt
"Add GitHub Actions caching to my Docker build so unchanged layers are reused between runs using
cache-fromandcache-toof type gha. Explain how layer caching saves time."
๐ Step-by-step
npm cache โ you already have it from lesson 02:
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: "npm" # caches ~/.npm automatically
Docker layer cache โ add to your build-push-action step:
- uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ghcr.io/${{ github.repository }}:latest
cache-from: type=gha
cache-to: type=gha,mode=max
cache-from: type=ghaโ pull cached layers from GitHub's cache.cache-to: type=gha,mode=maxโ save all layers (not just the final image) for next time.
The second run reuses unchanged layers and finishes far faster.
โ Done when
-
cache: "npm"is set onsetup-node - The Docker build uses
cache-from/cache-to: type=gha - A second run is noticeably faster than the first
๐ Quiz
Answer all 2 questions correctly to complete this lesson.