Docker 1 min read

Build a Smaller Go Image with a Multi-Stage Dockerfile

Build a Smaller Go Image with a Multi-Stage Dockerfile
Docker · November 30, 2026

Docker lab/version note: use supported Linux-container tools and patched images. Check version compatibility before running the examples. Docker, Swarm and platform-specific deployment steps were not tested live.

What this guide covers

A multi-stage Dockerfile uses one stage to test and compile code and another to run it. This keeps build tools out of the final application image. The example is a small Go HTTP server.

Before you start

Use Docker with BuildKit in a new directory. The example uses the Go standard library only. Select a supported Go release and matching builder image; the existing example uses the Go 1.26 line.

Step 1: Create the Go files

Save the module definition as go.mod:

// go.mod
module example.com/container-lab

go 1.26

Save the application as main.go:

package main

import (
    "fmt"
    "net/http"
)

func health(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "ok")
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/healthz", health)
    if err := http.ListenAndServe(":8080", mux); err != nil {
        panic(err)
    }
}

Save its test as main_test.go:

package main

import (
    "net/http/httptest"
    "testing"
)

func TestHealth(t *testing.T) {
    req := httptest.NewRequest("GET", "/healthz", nil)
    res := httptest.NewRecorder()
    health(res, req)
    if res.Code != 200 || res.Body.String() != "ok\n" {
        t.Fatalf("unexpected response: %d %q", res.Code, res.Body.String())
    }
}

Step 2: Create the Dockerfile

Exclude .git, environment files and local output in .dockerignore. Save this as Dockerfile:

# syntax=docker/dockerfile:1
FROM golang:1.26-alpine AS test
WORKDIR /src
COPY go.mod ./
COPY main.go main_test.go ./
RUN go test ./...

FROM test AS build
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server .

FROM scratch AS runtime
COPY --from=build /out/server /server
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/server"]

The test stage runs tests. build depends on that stage and compiles the binary. runtime copies only the binary and certificate bundle. scratch has no shell or package manager.

Step 3: Build and check the final image

Run:

docker build --target test -t go-lab:test .
docker build --pull --target runtime -t go-lab:1.0 .
docker image inspect go-lab:1.0 --format '{{.Config.User}} {{.Os}}/{{.Architecture}}'
docker image history go-lab:1.0
docker run -d --name go-lab --read-only --cap-drop ALL \
  --security-opt no-new-privileges=true \
  -p 127.0.0.1:8081:8080 go-lab:1.0
curl --fail http://127.0.0.1:8081/healthz

The HTTP response should be ok. The runtime uses a numeric non-root user. Debug it through logs and an approved diagnostic workflow rather than expecting a shell in the image.

Check the result

Check that tests fail the build when deliberately broken, then restore them and verify the runtime response. A small image still needs patching and application security review.

References

PB
Written by

Parul Bedi

Notes and guides by Parul Bedi.

Conversation

0 comments

No comments yet. Start the conversation below.

Leave a comment

Replying to a comment.
Be kind. Markdown is not supported in comments.