Cache build artifacts in a pipeline
4 min read
Overview
Every job on a SonicInfra GitHub Action Runner Set runs on its own freshly booted KubeVirt VM: the runner boots, picks up exactly one job, and powers off when it's done. That means a self-hosted runner's local disk doesn't carry anything over to the next job either — it's just as clean a slate as a GitHub-hosted runner. The fix is the same one you'd use on ubuntu-latest: actions/cache, which stores and restores files against GitHub's cache service over the network rather than relying on anything local to the runner.
This guide adds dependency caching to a workflow that already runs on a SonicInfra runner set.
Before you begin
- A GitHub Action Runner Set already created and
Ready— see Run CI on self-hosted GitHub Actions runners if you don't have one yet. - A workflow that targets it with
runs-on: <your-runner-set-name>.
Add a cache step
Add actions/cache before the step that installs dependencies. key should change whenever the dependency list changes — hashing the lockfile is the standard approach — and restore-keys lets a near-miss (same OS, older lockfile) still restore something instead of starting from empty:
jobs:
build:
runs-on: ci-runners
steps:
- uses: actions/checkout@v4
- name: Cache npm dependencies
uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-npm-
- name: Install and build
run: |
npm ci
npm run build
npm ci still re-links node_modules from ~/.npm's cache on every run, but it skips re-downloading anything that's already there — the expensive part on a clean runner.
The same pattern applies to other package managers: cache ~/.cache/pip for pip, ~/.cargo/registry for Cargo, ~/.m2/repository for Maven, and so on — whatever directory the tool downloads into.
Caching Docker image layers
If your build step runs docker build, use docker/build-push-action with its built-in GitHub Actions cache backend instead of actions/cache directly — it understands layer caching, actions/cache doesn't:
- uses: docker/build-push-action@v6
with:
context: .
cache-from: type=gha
cache-to: type=gha,mode=max