DEV Community

Cover image for The Complete Docker + Go Guide: From Beginner to Kubernetes Expert
Stanley Chege Thuita
Stanley Chege Thuita

Posted on Edited on

The Complete Docker + Go Guide: From Beginner to Kubernetes Expert

The short version: Go and Docker fit together unusually well: Go builds one static binary, and a container only needs that binary. This guide goes from a first Dockerfile to a production-ready image, and measures every claim on a real Go service: 1.38 GB down to 8 MB, 0.3 seconds to ready, and what actually happens to a request in flight when docker stop arrives, with and without signal handling. It also corrects several things the first version of this guide got wrong.

Contents

  1. Why Docker + Go
  2. The service we'll containerise
  3. The naive Dockerfile: 1.38 GB
  4. Multi-stage to scratch: 8 MB
  5. What each build flag buys
  6. What's inside a scratch image (and what isn't)
  7. Layer caching: order your COPY lines
  8. Graceful shutdown, measured
  9. Health checks without a shell
  10. Debugging and profiling
  11. Versions, vendoring and CI
  12. Docker Compose for local development
  13. Security checklist
  14. Corrections to the first version

Why Docker + Go

  • One static binary. With CGO_ENABLED=0, a Go program needs no C library, no interpreter and no runtime installed. The container can contain the binary and almost nothing else.
  • Small images. Measured below: 8 MB for a real HTTP service.
  • Fast start. Measured below: about 0.3 seconds from docker run to the first answered health check, most of it Docker's own work.
  • Same artifact everywhere. The image you test is the image you ship.

Install Docker Desktop on Mac or Windows, or Docker Engine on Linux (sudo apt install docker.io on Debian and Ubuntu, or Docker's own repository for newer versions).

The service we'll containerise

A small HTTP service with a health endpoint, a deliberately slow endpoint (to have a request in flight during shutdown), and graceful shutdown on SIGTERM. Go 1.22+ routing patterns ("GET /healthz") keep it dependency-free:

package main

import (
    "context"
    "errors"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok\n")) })
    mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
        time.Sleep(3 * time.Second) // an in-flight request when shutdown starts
        w.Write([]byte("finished\n"))
    })
    srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}

    if os.Getenv("NO_SIGNALS") == "1" { // the naive version: no signal handling at all
        log.Fatal(srv.ListenAndServe())
    }
    ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
    defer stop()
    go func() {
        if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
            log.Fatal(err)
        }
    }()
    log.Printf("listening on :8080 (pid %d)", os.Getpid())
    <-ctx.Done()
    log.Print("SIGTERM: draining in-flight requests")
    shutdownCtx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
    defer cancel()
    if err := srv.Shutdown(shutdownCtx); err != nil {
        log.Printf("shutdown: %v", err)
    }
    log.Print("stopped cleanly")
}
Enter fullscreen mode Exit fullscreen mode

ReadHeaderTimeout is there on purpose: an http.Server without one lets a slow client hold a connection open indefinitely (the "Slowloris" pattern), and the gosec linter flags it (rule G112). The NO_SIGNALS switch exists only so we can measure the difference later.

The naive Dockerfile: 1.38 GB

The obvious Dockerfile builds and runs in the same image as the Go toolchain:

FROM <a Go toolchain image>     # I used a cached Debian bookworm image with Go 1.26.6
WORKDIR /src
COPY go.mod main.go ./
RUN go build -o /kshop .
CMD ["/kshop"]
Enter fullscreen mode Exit fullscreen mode
docker build -f Dockerfile.single -t kshop:single .
Enter fullscreen mode Exit fullscreen mode

It works. It is also 1.38 GB: a whole Debian system, the Go compiler, the standard library sources and the build cache, all shipped to production to run one 7 MB binary. Every one of those files is attack surface and every byte is pull time on every deploy.

Multi-stage to scratch: 8 MB

A multi-stage build compiles in one image and copies only the result into another. The final stage starts FROM scratch, Docker's empty image:

# Stage 1: build with the full toolchain
FROM <a Go toolchain image> AS build
WORKDIR /src
COPY go.mod ./
RUN go mod download
COPY main.go ./
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /kshop .

# Stage 2: nothing but the binary
FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=build /kshop /kshop
USER 65534:65534
EXPOSE 8080
ENTRYPOINT ["/kshop"]
Enter fullscreen mode Exit fullscreen mode
$ docker images kshop --format '{{.Tag}} {{.Size}}'
scratch 8MB
single 1.38GB
Enter fullscreen mode Exit fullscreen mode

From 1.38 GB to 8 MB, about 170 times smaller, for the same program. In your own builds, use the official golang:1.26 (or newer) image as the builder; I used a Go 1.26.6 Debian image already on my machine to avoid pulling anything new.

What each build flag buys

Flag What it does Why
CGO_ENABLED=0 Pure-Go build, no C library linked The binary runs on scratch, which has no libc. Without it, packages like net and os/user may link against glibc and fail to start with a confusing "no such file" error
GOOS=linux Target Linux Needed when building on a Mac outside Docker; harmless inside
-trimpath Removes local file paths from the binary Reproducible builds, and your home directory doesn't leak into stack traces
-ldflags="-s -w" Strips the symbol table and DWARF debug info Smaller binary

Measured on this service (linux/arm64):

7796353  plain build
5374114  -trimpath -ldflags="-s -w"
Enter fullscreen mode Exit fullscreen mode

About 31% smaller. The trade-off: stripped binaries have no debug info, so attach Delve to a debug build instead (below). Stack traces from panics still work, because Go keeps the information it needs for those.

What's inside a scratch image (and what isn't)

docker history shows every layer:

0B  ENTRYPOINT ["/kshop"]
0B  EXPOSE [8080/tcp]
0B  USER 65534:65534
5.38MB  COPY /kshop /kshop # buildkit
233kB   COPY /etc/ssl/certs/ca-certificates.crt /etc…
Enter fullscreen mode Exit fullscreen mode

Two files. That's the whole image. Some consequences:

  • CA certificates must be copied in. Without ca-certificates.crt, any outgoing HTTPS call fails with x509: certificate signed by unknown authority. That 233 kB line is the fix.
  • No shell. You can't docker exec into it, and neither can an attacker:
$ docker run --rm --entrypoint sh kshop:scratch -c id
... exec: "sh": executable file not found in $PATH
Enter fullscreen mode Exit fullscreen mode
  • No time zone data. If you call time.LoadLocation("Africa/Nairobi"), add import _ "time/tzdata" to embed the database in the binary (about 450 kB), or copy /usr/share/zoneinfo from the build stage.
  • No users file, so USER takes numbers. 65534 is the conventional nobody. Running as non-root means a bug in your service can't write to the image's files or bind privileged ports.

If you need a little more (a CA bundle and time zones maintained for you, a non-root user by name), Google's distroless static image is the next step up; I haven't measured it here.

Layer caching: order your COPY lines

Docker caches each instruction's result and reuses it until an input changes. So copy what changes least first:

COPY go.mod go.sum ./
RUN go mod download        # cached until your dependencies change
COPY . .
RUN go build ...           # rebuilt when your code changes
Enter fullscreen mode Exit fullscreen mode

Copy everything first (COPY . . then go mod download) and every code change re-downloads every dependency. Add a .dockerignore so the build context doesn't drag in .git, local binaries or secrets:

.git
*.md
bin/
.env
Enter fullscreen mode Exit fullscreen mode

The .env line matters: anything in the build context can end up in an image layer, and image layers are easy to extract.

Graceful shutdown, measured

docker stop sends SIGTERM to the container's main process, waits (10 seconds by default), then sends SIGKILL. Kubernetes does the same when it scales down or rolls out. The question is what happens to requests in flight.

The test: start the container, wait for /healthz, start a request to /slow (3 seconds), and 0.5 seconds later run docker stop. Once with the handler above, once with NO_SIGNALS=1:

WITH signal handling:
  ready after 0.34 s (docker run to first /healthz)
  in-flight /slow got: 'finished'
  docker stop took 2.9 s, exit code 0
  log: listening on :8080 (pid 1)
  log: SIGTERM: draining in-flight requests
  log: stopped cleanly

WITHOUT signal handling (NO_SIGNALS=1):
  in-flight /slow got: ''
  docker stop took 0.2 s, exit code 2
Enter fullscreen mode Exit fullscreen mode

With handling, srv.Shutdown stops accepting new connections, waits for the in-flight request, and exits cleanly after about 2.9 seconds: the remaining 2.5 seconds of /slow, plus a little. The customer got their answer.

Without handling, the in-flight request got nothing: the connection dropped mid-request.

This surprised me, because the folk wisdom is "PID 1 ignores SIGTERM, so your container hangs for 10 seconds and gets killed". That's true for a process that installs no handler at all, because the Linux kernel doesn't apply default signal actions to PID 1. But the Go runtime installs its own signal handlers, and its default response to SIGTERM is to exit immediately with status 2. So a Go service without a handler doesn't hang; it dies instantly, mid-request. Adding --init (a tiny init process as PID 1 that forwards signals) changes only the exit code (143, meaning killed by signal 15); the request still dies.

The lesson: for Go, the danger isn't a slow shutdown, it's a fast one. Handle SIGTERM, call Shutdown with a deadline shorter than the platform's grace period (8 s under Docker's 10 s here), and in Kubernetes, also stop reporting ready before you stop serving, so the load balancer drains you first.

Health checks without a shell

The first version of this guide recommended a HEALTHCHECK instruction. On scratch the usual one, HEALTHCHECK CMD curl -f http://localhost:8080/healthz, can't work: there's no curl and no shell. Two options that do:

  1. Let the orchestrator check. Kubernetes probes and most load balancers call /healthz from outside the container. This is usually what you want.
  2. Make the binary its own checker. Add a flag that calls the endpoint and exits 0 or 1:
if len(os.Args) > 1 && os.Args[1] == "-health" {
    resp, err := http.Get("http://127.0.0.1:8080/healthz")
    if err != nil || resp.StatusCode != http.StatusOK {
        os.Exit(1)
    }
    os.Exit(0)
}
Enter fullscreen mode Exit fullscreen mode
HEALTHCHECK --interval=10s --timeout=2s CMD ["/kshop", "-health"]
Enter fullscreen mode Exit fullscreen mode

Use the exec form (["/kshop", "-health"]): the shell form (CMD /kshop -health) needs /bin/sh, which scratch doesn't have.

Debugging and profiling

Delve in a debug image. Keep debugging out of the production image; build a separate one with the toolchain and without -s -w:

FROM golang:1.26
RUN go install github.com/go-delve/delve/cmd/dlv@latest
WORKDIR /src
COPY . .
CMD ["dlv", "debug", "--headless", "--listen=:40000", "--api-version=2", "--accept-multiclient", "."]
Enter fullscreen mode Exit fullscreen mode
docker run -p 40000:40000 -p 8080:8080 kshop:debug
Enter fullscreen mode Exit fullscreen mode

Then attach your editor's debugger to port 40000. (The first version of this guide split that CMD JSON array over several lines without line continuations, which Docker rejects. Keep exec-form arrays on one line.)

pprof in production, carefully. import _ "net/http/pprof" registers profiling handlers on http.DefaultServeMux. Serve them on a separate, internal port, never on the public one: they expose memory contents and can be used to burn CPU.

go func() { log.Println(http.ListenAndServe("127.0.0.1:6060", nil)) }()
Enter fullscreen mode Exit fullscreen mode
go tool pprof http://localhost:6060/debug/pprof/heap
Enter fullscreen mode Exit fullscreen mode

Versions, vendoring and CI

Bake the version into the binary at build time:

ARG VERSION=dev
RUN CGO_ENABLED=0 go build -ldflags="-s -w -X main.version=${VERSION}" -o /kshop .
Enter fullscreen mode Exit fullscreen mode
docker build --build-arg VERSION=1.2.3 -t kshop:1.2.3 .
Enter fullscreen mode Exit fullscreen mode

Vendoring (go mod vendor, then go build -mod=vendor) puts every dependency in your repository, so builds need no network and survive a module proxy outage. The trade-off is a bigger repository; many teams rely on go.sum plus the module proxy instead.

Tag images with versions, not just latest. latest is whatever was pushed most recently, which makes rollbacks guesswork. Push kshop:1.2.3 and, if you want, latest as well, but deploy the versioned tag.

In CI, a reasonable minimum: go vet ./..., go test -race ./..., build the image, scan it, push the versioned tag on the main branch.

Docker Compose for local development

Compose runs the service with its dependencies. The top-level version: key is obsolete in Compose v2 and is ignored, so leave it out:

services:
  api:
    build: .
    ports:
      - "8080:8080"
    environment:
      DB_HOST: postgres
      REDIS_ADDR: redis:6379
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_started
    restart: unless-stopped

  postgres:
    image: postgres:18-alpine
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/pg_password
    secrets:
      - pg_password
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres"]
      interval: 5s
      retries: 10

  redis:
    image: redis:7-alpine

secrets:
  pg_password:
    file: ./pg_password.txt

volumes:
  pgdata:
Enter fullscreen mode Exit fullscreen mode

Two changes from the first version worth explaining. depends_on with condition: service_healthy waits until Postgres actually accepts connections, not just until its container started (a common source of "connection refused" on first boot). And the password comes from a secret file rather than a literal in the Compose file, which tends to get committed.

Kubernetes, init containers and sidecars now have their own post, the second part of this guide:


Security checklist

Area Do this Why
Base image scratch or distroless for Go Nothing to exploit that you didn't ship
User USER 65534:65534 A compromised process isn't root
Filesystem Run with a read-only root (--read-only, or readOnlyRootFilesystem: true) Nothing can be dropped into the container
Capabilities --cap-drop=ALL A web service needs none
Secrets Secret files or a secret manager; never ENV or build args ENV and ARG values are visible in image metadata and history
Build context .dockerignore with .env, .git Keeps secrets and history out of layers
Scanning Scan images in CI (for example trivy image kshop:1.2.3) Known CVEs in anything you did ship
Shutdown Handle SIGTERM, Shutdown with a deadline Measured above: unhandled means dropped requests
Resources Set CPU and memory limits One leak shouldn't take down the host
Tags Deploy versioned tags Reproducible deploys and rollbacks

Corrections to the first version

The first version of this guide (June 2026) had several things I've fixed above:

  1. "Fast startup (microseconds)." The Go binary starts in milliseconds; the container took about 0.3 seconds from docker run to answering, most of it Docker's own setup. Still fast, but not microseconds.
  2. The Delve CMD was a JSON array split over several lines, which Docker doesn't parse.
  3. HEALTHCHECK was recommended without noting it can't run curl in a scratch image.
  4. Compose used the obsolete version: key, a literal password, and a plain depends_on that doesn't wait for readiness.
  5. "Use env vars for secrets" was in the checklist; environment variables are visible to anything that can inspect the container, so secret files are the safer default.

Every number in this version comes from a build and run on my machine (Docker 29.8.1, Apple M1, Go 1.26.6 in the build stage). If something behaves differently on yours, tell me in the comments.

Top comments (0)