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

Members can save this page, take notes and track progress. See membership · Sign in

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

Download starter filesDownload finished project

Steps

  1. 1Write the API

    A minimal HTTP service with a /health endpoint, 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))
    }
    
  2. 2Declare the module

    go.mod
    module example.com/hello-api
    
    go 1.26
    
  3. 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"]
    
  4. 4The multi-stage Dockerfile

    Stage build compiles 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.mod is 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"]
    
  5. 5Keep the build context small

    Everything in the folder is sent to the builder unless .dockerignore excludes it.

    .dockerignore
    .git
    *.md
    Dockerfile*
    .dockerignore
    
  6. 6Build both and compare

    Run
    docker build -f Dockerfile.naive -t lab-hello:naive .
    docker build -t lab-hello:multi .
    docker images lab-hello
    

    Expected 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.

  7. 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-hello
    

    Expected output

    {"message":"hello from a container","version":"1.0.0"}
    ok
    2026/11/26 01:45:17 listening on :8080
  8. 8Rebuild without changes: everything is cached

    --progress=plain shows each step. Unchanged inputs mean every step is CACHED (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
  9. 9Change the code: dependencies stay cached

    Edit the version string in main.go to 2.0.0 and rebuild. Steps up to go mod download are still CACHED; only COPY . . 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 . . and go build have no CACHED line; the steps before them do.

  10. 10Change the dependencies: the download re-runs

    Changing go.mod invalidates its COPY layer and every step after it. This is why dependency files are copied first: they change rarely, source changes often. Afterwards, remove the require line again and set the version back to 1.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 download runs again. The last line is CACHED because the binary came out identical.

  11. 11See what .dockerignore saves

    Create a 50 MB file the build doesn't need, then build with and without .dockerignore and 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.md
    

    Expected 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.

  12. 12Clean up

    Run
    docker rm -f lab-hello
    docker image rm lab-hello:naive lab-hello:multi lab-hello:dep lab-hello:noignore
    
    Check:

    docker images lab-hello lists 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

  1. Copy dependency manifests (go.mod, package.json + lock file, requirements.txt, pom.xml) first.
  2. Install dependencies in their own RUN step.
  3. Copy the source last.
  4. Keep .dockerignore strict: .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
  • .dockerignore excludes .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

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake