25 KiB
CI/CD build cache — apply to any repo
Copy this into another service when CI or tag-deploy is slow. It is stack-agnostic. The worked example is GrowthOS (phase-3b-plan.md, live .gitea/workflows/). A one-image copy-paste is templates/.
Objective: cut wall-clock, not image size. Engineer wait and runner minutes first.
Assumes: Gitea Actions + act_runner labelled ubuntu-latest, host Docker, a Gitea registry, Compose on one VM. One runner unless the checklist says otherwise. BuildKit is the default builder. No QEMU/--platform unless you measured a real multi-arch need.
Gitea queues jobs; Gitea Runner executes them. runs-on: ubuntu-latest is a registered label, not a GitHub-hosted VM.
Runner behaviour is a variable, not a constant. Labels, container.network, capacity, cache reachability, and whether workflow-supplied container options survive all come from the runner's config.yaml and its version. Measure them; do not inherit them from a blog post or from this file. platform/observed-state.md is this fleet's measured state and the source of truth for every runner-dependent rule below — including two that were wrong here until 2026-09-28.
Assumed execution mode: Docker with the host socket. Jobs are isolated from each other; they share the daemon. That is why BuildKit cache mounts and a named buildx builder survive across tags. DinD wipes that persistence; host mode has no job isolation. Do not copy this playbook onto those modes without re-measuring.
GITEA_TOKEN cannot publish to the container registry. CD must keep REGISTRY_USERNAME / REGISTRY_TOKEN (a PAT). The same token is injected into every job and the instance is reachable from job containers — see §8. Do not let product code treat it as an app PAT.
A second registered runner is the first time extra Gitea jobs shorten wall clock. Until then, parallelism is bake and BuildKit stages only.
1. Measure before changing flags
docker build --progress=plain (CD) and the last green job timestamps (CI). Attribute every minute to one bucket:
| Bucket | Symptom | Usual fix |
|---|---|---|
| Context upload | Pause before the first step | .dockerignore at the context root |
| Dependency install | restore / npm ci / pip dominates |
Layer order, then cache mounts + a CI cache backend |
| Compilation | publish / vite / go build |
Native arch first; then incremental caches |
| Push | Job sits after “exporting to image” | One buildx --push with all tags; smaller final image last; turn off default provenance |
| Serialisation | Independent work in one chain | Bake / parallel stages, not more jobs on one runner |
Record the numbers in the PR. Do not add cache-to until this baseline exists.
GrowthOS backend on this fleet (2026-09-28, green, e2-standard-2): restore 2m7s, build 10m12s (was 20–30 min), unit 4m34s (was 13m31s abort), integration 6m0s green. GrowthOS CD tag (2026-09-29, green, capped bake): build-and-push 15m48s (bake 14m29s), migrate 1m32s, deploy 1m12s — Gitea stayed up. Source: platform/observed-state.md Host budget.
Emulation (QEMU, --platform linux/amd64 on arm64) is 5–20× on compile. If you see it, fix architecture before Dockerfiles.
2. Symptoms that mean “do this guide”
| You see | It means |
|---|---|
COPY . . then dotnet restore / npm ci / pip install |
Every source edit reinstalls. Junior cache miss. |
CD builds --target final, next job builds --target migrate |
Fourth cold SDK restore. Same graph, thrown away. |
Three docker build + two docker push each |
Sequential images + extra tag round-trips. |
Cache export is not supported for the docker driver |
Bake used the default builder. Need docker-container for cache-to. |
Could not find file '…/.nuget/packages/…/*.nuspec' |
Concurrent restores wrote the same cache id. Split ids or lock restore only. |
setup-node has cache: npm, setup-dotnet has none |
.NET pays a cold NuGet every job. |
Unit tests abort / hang-dump / OOM on a large AppDbContext |
A new EF InMemory provider per database name recompiles the model. Share one internal provider and one InMemoryDatabaseRoot; isolate by name. |
Integration tests fail with 57P03 (recovery mode) after a few minutes |
Testhost used both vCPUs and crashed the service Postgres. Cap every dotnet test step (DOTNET_PROCESSOR_COUNT=1). pg_isready can still pass — wait for queries. |
| CD bake / registry push stalls Gitea (504) or freezes the VM | Bake compiled every target at once, or one compile used both cores and swap. One Gitea job, cap-buildx-builder.sh (--cpus=1 --memory=3g --memory-swap=3g), bake one target at a time. BUILDKIT_STEP_MAX_PARALLELISM=1 is not enough. |
docker create fails: no command specified after a green migrate bake |
Scratch migrate-bundle has no CMD. Set CMD ["/out/migrate-api"] and docker create IMAGE /out/migrate-api. |
importing cache manifest …:buildcache: not found |
First tag (or pruned cache). Non-fatal — bake continues; cache-to creates the ref. Gate on the second tag. |
| A second job that only runs fixture tests | Second SDK + restore + implicit build. |
vue-tsc in lint and in npm run build |
Typecheck twice. |
Path filter is ** / the whole app tree |
Vue-only PR starts Postgres and restores the sln. |
Three CI jobs on one act_runner |
Wall clock is the sum, not the max. |
3. Dockerfile: restore-first, then cache mounts
Layer cache is per instruction. The first miss invalidates everything after it.
Wrong
COPY . .
RUN npm ci
Right — lockfile, install, then source
# syntax=docker/dockerfile:1
COPY package.json package-lock.json ./
RUN --mount=type=cache,id=npm,target=/root/.npm \
npm ci
COPY . .
Same shape everywhere. Copy each manifest into its own directory — COPY src/*/*.csproj ./src/ flattens paths and breaks restore.
| Ecosystem | Copy first | Then | Cache mount |
|---|---|---|---|
| Node | package.json + package-lock.json |
npm ci |
/root/.npm (id=npm) |
| .NET | *.sln + each *.csproj + .config/dotnet-tools.json |
dotnet restore the startup project, not the sln if the sln lists tests you excluded |
/root/.nuget/packages (id=nuget-api / nuget-worker) |
| Python | requirements.txt / uv.lock / poetry.lock |
pip / uv sync |
/root/.cache/pip |
| Go | go.mod + go.sum |
go mod download |
/go/pkg/mod and /root/.cache/go-build |
| Rust | Cargo.toml + Cargo.lock |
cargo fetch |
/usr/local/cargo/registry |
Same id= only when restores are not concurrent. Bake of API + Worker needs one id per image (nuget-api, nuget-worker). A shared id=nuget with default sharing=shared corrupts NuGet (*.nuspec missing, leftover extract files).
sharing=locked on restore only. Publish / ef bundle remount sharing=shared. A locked mount is held for the whole RUN, so locking publish serializes compile across bake targets.
Shared restore for sibling stages
If build and migrate (or api and worker) both start FROM sdk + COPY . . + restore, they do not share a layer. One restore stage, then:
FROM restore AS build
COPY . .
RUN --mount=type=cache,id=nuget-api,sharing=shared,target=/root/.nuget/packages \
dotnet publish src/Api/Api.csproj -c Release -o /app/publish --no-restore
FROM restore AS migrate
COPY . .
RUN --mount=type=cache,id=nuget-api,sharing=shared,target=/root/.nuget/packages \
dotnet ef migrations bundle ... --output /out/migrate-api --force
# Slim image for `type=docker` load — do not export the SDK stage to the daemon.
# scratch has no default command; without CMD, `docker create` fails with
# "no command specified".
FROM scratch AS migrate-bundle
COPY --from=migrate /out/migrate-api /out/migrate-api
CMD ["/out/migrate-api"]
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "Api.dll"]
Restore itself uses sharing=locked on the same id=nuget-api. Worker’s Dockerfile uses id=nuget-worker.
final must stay last so a bare docker build cannot ship the SDK. CD pins --target final for the runtime image and --target migrate-bundle for the artefact. Do not COPY --from=build the publish folder into migrate — ef bundle needs the SDK and project graph.
Cache mounts are builder-local. They survive on a persistent Docker-mode act_runner (shared host daemon). They do nothing on DinD or a wiped builder until §5.
4. Context
.dockerignore sits next to the context root (the directory you pass to docker build), not next to a Dockerfile in a subdirectory unless that subdirectory is the context.
Exclude whatever the image does not compile:
web/andtests/from an API/Worker context so a Vue or test edit cannot bust restorenode_modules,bin/,obj/,.git,.env*,dist/
A fat context costs transfer, cache keys, and leaked secrets. Name all three when you add the file.
5. CD: one bake, registry cache, no second compile
Replace sequential docker build + docker push + docker push :latest with docker buildx bake. One graph, both tags, one Gitea job.
On one runner, do not split API/Worker/Web into three Gitea jobs — they queue. Bake is how those images share a graph. “Scale the runner” means a second registered runner, not more YAML.
On this fleet (e2-standard-2 + Gitea) do not let bake compile every target at once, and do not trust BUILDKIT_STEP_MAX_PARALLELISM=1 to leave Gitea a core. A single dotnet publish still uses both vCPUs and will swap-thrash 8 GB (UI 504). Keep one Gitea job. Before bake, run scripts/cap-buildx-builder.sh so buildkitd is --cpus=1 --memory=3g --memory-swap=3g. Then docker buildx bake <target> one target at a time so registry push cannot overlap the next compile. SDK stages set DOTNET_PROCESSOR_COUNT=1; Node stages keep a small heap (NODE_OPTIONS=--max-old-space-size=512). Measured 2026-09-29: bake 14m29s, Gitea stayed up.
If Gitea is already 504: GCP Reset (keeps the ephemeral IP — never Stop/Start), then scripts/runner-host.sh reclaim. The Actions UI cannot cancel a wedged job.
cache-to (registry) needs the docker-container driver. The default docker builder cannot export cache even when buildx is installed. Inspect of a missing builder is expected: keep it inside cap-buildx-builder.sh so bash -e -o pipefail does not abort the step.
# Paths: bake resolves relative to the HCL file unless you use cwd://
# CD from git root → cwd://<context-dir>
variable "REGISTRY" {}
variable "TAG" {}
group "default" {
targets = ["api", "migrate", "worker", "web"]
}
target "api" {
context = "cwd://app"
dockerfile = "src/Api/Dockerfile"
target = "final"
tags = ["${REGISTRY}/api:${TAG}", "${REGISTRY}/api:latest"]
cache-from = ["type=registry,ref=${REGISTRY}/api:buildcache"]
cache-to = ["type=registry,ref=${REGISTRY}/api:buildcache,mode=max"]
}
target "migrate" {
context = "cwd://app"
dockerfile = "src/Api/Dockerfile"
target = "migrate-bundle"
tags = ["migrate-bundle:local"]
cache-from = ["type=registry,ref=${REGISTRY}/api:buildcache"]
# no cache-to — api already exports this Dockerfile at mode=max
}
mode=max exports intermediate stages (restore, build, migrate). Default min only keeps final (runtime) and looks like “cache does not work.”
mode=max is a second registry write. On a small service it is cheaper than a cold SDK restore. If cache export dominates the log, drop cache-to on the smallest image first.
bash CICD/scripts/cap-buildx-builder.sh app-builder
bake_one() {
local target="$1"
shift
BUILDX_NO_DEFAULT_ATTESTATIONS=1 docker buildx bake \
--progress=plain \
"$target" \
"$@" \
-f docker-bake.hcl
}
bake_one api --push --set api.output=type=image,push=true
sleep 8
bake_one worker --push --set worker.output=type=image,push=true
sleep 8
bake_one web --push --set web.output=type=image,push=true
sleep 8
bake_one migrate --set migrate.output=type=docker
--push on bake plus type=docker on the slim migrate-bundle target: runtime images go to the registry; the SDK stage is not loaded into the daemon and is not published.
Restrict --cache-to to trusted tag / workflow_dispatch workflows. Fork PR CI must not write buildcache (cache poisoning).
Migrate / extra artefact
Do not rebuild --target migrate in a later job. Bake the slim bundle in build-and-push, then:
docker create IMAGE /out/migrate-api+docker cpthe binary (act_runner bind mounts resolve on the Docker host, not the job workspace — neverdocker run -vfor this). Pass the path as the create command, or setCMDon the scratch stage — otherwise Docker returnsno command specified.actions/upload-artifactthe file- The migrate/deploy job
download-artifact, SCP, run on the host that can reach Postgres
Do not rely on “the previous job left an image on the host.” That dies on prune or a second runner.
Do not push the migrate/SDK image. Do not type=docker the SDK migrate stage — that load is most of the tail.
6. CI: cache installs, fold jobs, skip the other stack
CI is not an image-build problem. Do not docker build in CI because CD is slow.
Cache the toolchain the frontend already cached
- uses: actions/setup-dotnet@v4
with:
dotnet-version: "8.0.x"
cache: true
cache-dependency-path: "**/*.csproj" # lockfile if you have one
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
cache-dependency-path: web/package-lock.json
Gitea actions/cache (behind cache: true) is runner config, not something the workflow can invent. On this fleet it hits — setup-dotnet cache: and setup-node cache: npm are real. If a copy-paste job no-ops, the operator must enable the runner’s cache backend — or set NUGET_PACKAGES / npm_config_cache to a host path the Docker-mode runner keeps. One mechanism, then measure. See platform/observed-state.md.
Cap testhost on every test step
Not only unit tests. Copy onto unit, integration, and eval steps:
env:
DOTNET_PROCESSOR_COUNT: "1"
DOTNET_gcServer: "0"
DOTNET_GCHeapCount: "1"
Serialize xUnit (xunit.runner.json maxParallelThreads: 1 plus -- xUnit.MaxParallelThreads=1). Tests that --no-build after the sln compile. InMemory unit tests in a job whose env points at service Postgres/Redis must blank those connection strings for the unit-test step, or AppDbContextFactory will hammer the live DB.
Postgres service: --shm-size=256mb (honoured on this runner with Privileged=false) and a start-period long enough that pg_isready is not the only gate. Tests wait until queries work — 57P03 is crash recovery, not a flaky assertion.
Fold jobs that only exist to compile again
A fixture/eval assembly that the sln already builds belongs after dotnet build with --no-build. A second job is a second checkout + SDK + restore.
Keep assemblies sequential in one job if they would share a TRX filename. Splitting unit vs integration on one runner makes the queue longer.
Path-filter so the other stack does not run
Workflow-level paths: still lists the app. Job-level: skip backend (and its Postgres/Redis services) when only the SPA changed.
| Changed | Run |
|---|---|
web/** only |
frontend |
src/**, tests/**, *.sln, .config/** |
backend |
.gitea/workflows/** |
both |
| both stacks | both |
On one runner, a cheap changes job (checkout + git diff) is worth it because it avoids starting service containers. Native paths: on two workflow files is the same outcome with no extra job.
Not running is faster than any cache.
Typecheck / lint once
If lint is vue-tsc --noEmit and build is vue-tsc -b && vite build, CI should run one vue-tsc then vite build. Keep the full script for laptops.
7. Runner economics (one act_runner)
| Parallelism | Use when |
|---|---|
BuildKit stages + bake |
Independent images/stages in one CD job |
cap-buildx-builder.sh + one bake target at a time |
This host — leave Gitea a vCPU; --cpus=1 on buildkitd |
| Fewer CI jobs + path filters | Same runner; skip work |
| More Gitea jobs | Once runner.capacity > 1, or a second runner exists |
Adding Gitea jobs to a runner with capacity: 1 queues them — wall clock is the sum, not the max.
The first lever is runner.capacity in the runner's config.yaml (default 1), not a second machine: it runs N jobs concurrently on the same runner. Do not raise it on this fleet. The host is GCP e2-standard-2 (2 vCPU / 8 GB) and also runs Gitea — see platform/observed-state.md Host budget. Two concurrent .NET jobs plus service containers will starve Gitea. Path filters skip unused jobs; a standalone frontend job only overlaps once the VM is bigger or a second runner exists.
Cap every dotnet test / eval step in the job (DOTNET_PROCESSOR_COUNT=1, workstation GC), not only unit tests. Default ProcessorCount is 2 — the whole machine. Uncapped integration testhost crashed service Postgres (57P03). Same idea for Node if a job pegs both cores.
A second registered runner comes after capacity is exhausted, and is what cache.external_server (a shared cache server) exists for — caches are per-runner otherwise.
Persistent Docker-mode host Docker is the “persistent builder” in the docker reference — the only place cache mounts survive without exporting cache. Do not buy Depot / bigger runners until layer order + registry cache + path filters are in.
8. Invariants to keep while speeding up
Copy these only if they already apply. Do not invent them for a repo that does not have them.
| Rule | Why it exists |
|---|---|
final last; CD --target final |
Bare docker build must not ship SDK/CMD bash |
Slim migrate-bundle + CMD + docker create IMAGE /out/migrate-api + docker cp |
act_runner bind mounts are host-scoped; do not load the SDK image. Scratch without CMD fails create with no command specified. |
| Migrate on the deploy network, not the runner | Postgres is not on the runner; Host=postgres only resolves there |
| Connection strings as SCP files | Remote shell splits on ; |
Job graph build → migrate → deploy → smoke → image rollback |
Do not flatten migrate into deploy |
| CI DB/Redis by service name, never published on host ports | With container.network: "" the runner builds a per-job network with DNS aliases, so Host=postgres / redis:6379 work. Publishing collides with the runner host's own 5432/6379. (Under container.network: bridge there are no aliases — that is what the old high-port + host-discovery workaround existed for. Check platform/observed-state.md before assuming either.) |
| Testcontainers only when CI env is unset | CI services already provide the database |
No continue-on-error on tests |
A red suite must fail the job |
| PAT for registry login | GITEA_TOKEN cannot push packages |
Toolchain image mirrored into the Gitea registry, digest-pinned, force_pull: false |
runs-on: resolves to a label, and the label is the image every job runs in. A third-party moving tag on a public registry is an unpinned toolchain re-pulled on the critical path of every build. Mirror it, pin by digest, keep the package public so the runner pulls anonymously, and record the digest — see the toolchain log in platform/observed-state.md. A pinned base receives no upstream fixes until someone re-mirrors it, so the cadence needs an owner. |
Blank GITEA_TOKEN + product Gitea BaseUrl/DryRun in CI when tests must stay offline |
Every job receives GITEA_TOKEN; job containers can reach this Gitea. Appsettings DryRun: true loses to env. Live Contents/Pulls from CI is a product write, not a fixture. See platform/observed-state.md. |
Cap testhost cores/GC on every test/eval step (DOTNET_PROCESSOR_COUNT=1, workstation GC) |
Host is e2-standard-2 (2 vCPU / 8 GB) and also runs Gitea + the runner. Default testhost uses every core. Uncapped integration testhost crashed service Postgres (57P03). |
Cap CD bake (cap-buildx-builder.sh cgroup + one target at a time; DOTNET_PROCESSOR_COUNT=1 in SDK stages) |
Default bake compiles every target at once. BUILDKIT_STEP_MAX_PARALLELISM=1 still lets one compile take both cores and 504 Gitea. Keep one job; cap buildkitd; serialize targets. |
Wait for Postgres queries, not only pg_isready; --shm-size on the service |
pg_isready can pass while the engine is in crash recovery (57P03). Tests retry until SELECT works. |
One EF InMemory provider + one InMemoryDatabaseRoot per test assembly; isolate by database name |
A new provider per name recompiles a large AppDbContext and OOMs this VM. A new root under UseInternalServiceProvider throws. |
9. Order of work on the next repo
- Measure CD (
--progress=plain) and CI timestamps; write the five buckets in the PR. .dockerignore+ restore-first Dockerfiles + sharedrestoreif two stages restore the same graph.- Cache mounts:
sharing=lockedon restore,sharing=sharedon compile; split ids if bake restores in parallel. docker-bake.hcl+cap-buildx-builder.sh+ onebuildx bake <target>at a time +BUILDX_NO_DEFAULT_ATTESTATIONS=1; slimmigrate-bundle(CMD+type=docker);docker create IMAGE /out/migrate-api; artefact the binary.- Registry
cache-from/cache-tomode=maxon trusted CD only. - CI: NuGet/npm cache (runner cache backend or host path), fold eval jobs, path filters, one typecheck, testhost cap on every test step.
- Gate on the second run (unchanged lockfiles) and a frontend-only push that does not start Postgres.
Do not start with image-size work, Bazel, hermetic graphs, or a second runner.
10. Gate checklist
CD
- Second tag uses the container builder (no
Cache export is not supported for the docker driver) - Builder container is
--cpus=1 --memory=3g(docker inspectHostConfig); CD bakes one target at a time - Scratch
migrate-bundlehasCMD; extract usesdocker create IMAGE /out/migrate-api(not bare create) - Second tag on unchanged lockfiles/csproj: restore layer
CACHED(or NuGet mount skips the network) - First-tag
buildcache: not founddid not fail the job; second tag imports cache - Migrate/extra job has no
docker build - No SDK/migrate image in the registry
- Smoke + image-tag rollback unchanged
- Gitea UI stayed responsive during bake (no 504)
CI
- Second push on unchanged lockfiles: NuGet and/or npm cache hit
- Fixture/eval tests use
--no-buildon the sln output web/**-only push does not start the backend job (no Postgres)src/**-only push does not run the frontend job- CI does not
docker build - Every
dotnet test/ eval step setsDOTNET_PROCESSOR_COUNT=1(workstation GC) - Integration tests wait for Postgres queries (
57P03), not onlypg_isready - xUnit collections are serial (
maxParallelThreads=1)
Worked example
GrowthOS (this repo): docs/plans/phase-3b-plan.md. One-image template: templates/.
| Piece | Path |
|---|---|
| API restore + migrate + final | GrowthOS/src/GrowthOS.Api/Dockerfile |
| Worker | GrowthOS/src/GrowthOS.Worker/Dockerfile |
| Web npm cache mount | GrowthOS/web/Dockerfile |
| Bake | GrowthOS/docker-bake.hcl |
| Cap BuildKit cgroup | CICD/scripts/cap-buildx-builder.sh |
| Reclaim wedged host | CICD/scripts/runner-host.sh |
| CD bake + artefact | .gitea/workflows/cd.yml |
| CI changes + folded evals | .gitea/workflows/ci.yml |
| One-image bake example | CICD/templates/docker-bake.hcl |
| One-image CD example | CICD/templates/workflows/cd.yml |
Measured runner state (labels, network, capacity, cache, versions): platform/observed-state.md.
Interview depth behind the levers: docs/Reference/junior/docker (layer order, context), mid (cache mounts, CI cache, measuring), senior (build less, persistent builder, mode=max cost).