Docker Labs · Lab 2 of 6
Small, Fast Images with Multi-Stage Builds
Containerise a small Go API twice — once naively, once with a multi-stage build — compare a 492 MB image with a 15 MB one, and learn how layer caching and .dockerignore make rebuilds fast.
- Environment
- Local
- Level
- Beginner
- Time
- About 35 min
- Cost
- Free
You will build
A production-style Dockerfile for a compiled service: build in one stage, ship only the binary on a minimal base image, with dependency layers cached so a code change rebuilds in seconds.
Before you start
- Lab: Docker Basics: Containers, Images, Volumes and Networks
Docker with BuildKit (the default since Docker 23)
You don't need Go installed: the build runs inside the golang image. The same pattern works for Java (build
with Maven, ship a JRE), Node (install and build, ship dist/) and Rust.
Container IDs, image IDs, timestamps and sizes will differ on your machine; everything else should match.
Project structure
hello-api/ ├── main.go # a tiny JSON API on :8080 ├── go.mod ├── Dockerfile.naive # one stage: toolchain included ├── Dockerfile # two stages: only the binary ships └── .dockerignore
Steps
-
1Write the API
A minimal HTTP service with a
/healthendpoint, the kind every container platform probes.main.go package main import ( "encoding/json" "log" "net/http" "os" ) func main() { port := os.Getenv("PORT") if port == "" { port = "8080" } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"message": "hello from a container", "version": "1.0.0"}) }) http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) }) log.Printf("listening on :%s", port) log.Fatal(http.ListenAndServe(":"+port, nil)) } -
2Declare the module
go.mod module example.com/hello-api go 1.26 -
3The naive Dockerfile
Build and run in the same image. It works — but it ships the whole Go toolchain to production.
Dockerfile.naive FROM golang:1.26-alpine WORKDIR /src COPY . . RUN go build -o /server . EXPOSE 8080 CMD ["/server"] -
4The multi-stage Dockerfile
Stage
buildcompiles a static binary (CGO_ENABLED=0). The final stage starts from distroless, an image with no shell or package manager, and copies in only the binary.go.modis copied and downloaded before the source, so dependency downloads are cached separately from code changes.Dockerfile # Stage 1: build with the full Go toolchain FROM golang:1.26-alpine AS build WORKDIR /src COPY go.mod ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /server . # Stage 2: ship only the binary FROM gcr.io/distroless/static-debian13 COPY --from=build /server /server EXPOSE 8080 ENTRYPOINT ["/server"] -
5Keep the build context small
Everything in the folder is sent to the builder unless
.dockerignoreexcludes it..dockerignore .git *.md Dockerfile* .dockerignore -
6Build both and compare
Run docker build -f Dockerfile.naive -t lab-hello:naive . docker build -t lab-hello:multi . docker images lab-helloExpected output
... IMAGE ID DISK USAGE CONTENT SIZE EXTRA lab-hello:multi 644bb78315f9 15.2MB 3.4MB lab-hello:naive d95bab5eb0a9 492MB 98MB
Check:The multi-stage image is about 30 times smaller.
-
7Run the small image
Run docker run -d --name lab-hello -p 8080:8080 lab-hello:multi curl -s localhost:8080/ curl -s localhost:8080/health docker logs lab-helloExpected output
{"message":"hello from a container","version":"1.0.0"} ok 2026/11/26 01:45:17 listening on :8080 -
8Rebuild without changes: everything is cached
--progress=plainshows each step. Unchanged inputs mean every step isCACHED(BuildKit may list them in any order).Run docker build --progress=plain -t lab-hello:multi . 2>&1 | grep -E '^#[0-9]+ \[(build|stage)|CACHED'Expected output
#5 [stage-1 1/2] FROM gcr.io/distroless/static-debian13:latest@sha256:15f8637509792e05b97d83451b0b6ccfa4abd548f997e406ac1e72c87fe1fa78 #6 [build 1/6] FROM docker.io/library/golang:1.26-alpine@sha256:27f2d3b83cfc5803c8078f8e730af0f7c431bf067afaec8f60a36fb763187cba #8 [build 4/6] RUN go mod download #8 CACHED #9 [build 3/6] COPY go.mod ./ #9 CACHED #10 [build 2/6] WORKDIR /src #10 CACHED #11 [build 5/6] COPY . . #11 CACHED #12 [build 6/6] RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /server . #12 CACHED #13 [stage-1 2/2] COPY --from=build /server /server #13 CACHED
-
9Change the code: dependencies stay cached
Edit the version string in
main.goto2.0.0and rebuild. Steps up togo mod downloadare stillCACHED; onlyCOPY . .and the compile run again.Run docker build --progress=plain -t lab-hello:multi . 2>&1 | grep -E '^#[0-9]+ \[(build|stage)|CACHED'Expected output
#5 [stage-1 1/2] FROM gcr.io/distroless/static-debian13:latest@sha256:15f8637509792e05b97d83451b0b6ccfa4abd548f997e406ac1e72c87fe1fa78 #6 [build 1/6] FROM docker.io/library/golang:1.26-alpine@sha256:27f2d3b83cfc5803c8078f8e730af0f7c431bf067afaec8f60a36fb763187cba #8 [build 2/6] WORKDIR /src #8 CACHED #9 [build 3/6] COPY go.mod ./ #9 CACHED #10 [build 4/6] RUN go mod download #10 CACHED #11 [build 5/6] COPY . . #12 [build 6/6] RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /server . #5 [stage-1 1/2] FROM gcr.io/distroless/static-debian13:latest@sha256:15f8637509792e05b97d83451b0b6ccfa4abd548f997e406ac1e72c87fe1fa78 #5 CACHED #13 [stage-1 2/2] COPY --from=build /server /server
Check:COPY . .andgo buildhave noCACHEDline; the steps before them do. -
10Change the dependencies: the download re-runs
Changing
go.modinvalidates itsCOPYlayer and every step after it. This is why dependency files are copied first: they change rarely, source changes often. Afterwards, remove therequireline again and set the version back to1.0.0.Run printf '\nrequire golang.org/x/text v0.30.0\n' >> go.mod docker build --progress=plain -t lab-hello:dep . 2>&1 | grep -E '^#[0-9]+ \[(build|stage)|CACHED'Expected output
#5 [build 1/6] FROM docker.io/library/golang:1.26-alpine@sha256:27f2d3b83cfc5803c8078f8e730af0f7c431bf067afaec8f60a36fb763187cba #6 [stage-1 1/2] FROM gcr.io/distroless/static-debian13:latest@sha256:15f8637509792e05b97d83451b0b6ccfa4abd548f997e406ac1e72c87fe1fa78 #8 [build 2/6] WORKDIR /src #8 CACHED #9 [build 3/6] COPY go.mod ./ #10 [build 4/6] RUN go mod download #11 [build 5/6] COPY . . #12 [build 6/6] RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /server . #13 [stage-1 2/2] COPY --from=build /server /server #13 CACHED
Check:go mod downloadruns again. The last line isCACHEDbecause the binary came out identical. -
11See what .dockerignore saves
Create a 50 MB file the build doesn't need, then build with and without
.dockerignoreand compare the build context sent to the builder.Run dd if=/dev/zero of=big-notes.md bs=1M count=50 status=none docker build --progress=plain -t lab-hello:multi . 2>&1 | grep "transferring context" mv .dockerignore dockerignore.off docker build --progress=plain -t lab-hello:noignore . 2>&1 | grep "transferring context" mv dockerignore.off .dockerignore && rm big-notes.mdExpected output
#4 transferring context: 76B done #7 transferring context: 674B done #4 transferring context: 2B done #7 transferring context: 52.44MB 0.2s done
Check:674 bytes with
.dockerignore, 52 MB without it. -
12Clean up
Run docker rm -f lab-hello docker image rm lab-hello:naive lab-hello:multi lab-hello:dep lab-hello:noignoreCheck:docker images lab-hellolists nothing.
In production
Image size isn't vanity. Smaller images pull faster (quicker deploys and autoscaling), cost less to store and transfer, and contain fewer packages that can carry vulnerabilities.
What changes
| In this lab | In production |
|---|---|
golang:1.26-alpine and distroless/static-debian13:latest by tag |
Base images pinned by digest and updated deliberately (Renovate or Dependabot opens the PR) |
| Cache lives on your laptop | CI uses a shared build cache (cache-to: type=gha or a registry cache) so builds stay fast on fresh runners |
| The container runs as distroless's default user | The :nonroot variant or an explicit USER (see the hardened-images lab) |
version hard-coded in main.go |
Version and git commit injected at build time with --build-arg and -ldflags |
| You compare sizes by eye | CI fails the build if the image grows past a budget or the scan finds high-severity issues |
Ordering rules that keep builds fast
- Copy dependency manifests (
go.mod,package.json+ lock file,requirements.txt,pom.xml) first. - Install dependencies in their own
RUNstep. - Copy the source last.
- Keep
.dockerignorestrict:.git, local env files, build output, test data.
Production checklist
- Final stage contains only the runtime artefact and what it needs (no compilers, no package manager)
- Base images pinned by digest; an automated update process exists
- Dependency install is a separate, cacheable layer
.dockerignoreexcludes.git, secrets, local builds and large data- Builds are reproducible in CI, not only on a developer laptop
- Image size is tracked; a sudden jump fails review
Learn the concepts
- Writing a Dockerfile · Docker Tutorial
- Multi-Stage Builds · Docker Tutorial
- Layer Caching and Fast Builds · Docker Tutorial
- The Build Context and .dockerignore · Docker Tutorial
- Choosing a Base Image · Docker Tutorial
- Docker from Basics to Production · Course