Skip to main content

Containers and Kubernetes · Intermediate · 22 min

Package the Snip Go API in a distroless container image

By Padding · Updated 18 Nov 2026
Debian 13 (golang:1.27 image) · Go 1.27.4 · pgx 5.13.0 · distroless static-debian13 · Docker Engine 29 · kind 0.33

You will write Snip, a small Go 1.27 link-shortener API with health and readiness endpoints and a clean drain on SIGTERM, build it as a static binary, package it in a two-stage Dockerfile on a distroless non-root base, and load the image into a kind cluster.

On this page

This series takes one small API from source code to a production-like Kubernetes deployment. The API is Snip, a link shortener: you send it a long address, it gives you a six-character code, and requesting /<code> redirects to the address. It keeps links in PostgreSQL 18 when DATABASE_URL is set and in memory otherwise, so this first part needs no database.

Kubernetes expects three things from a program before it can look after it well. It needs a way to ask "are you alive?" and "should I send you traffic?", which you answer with /healthz and /readyz. It sends SIGTERM before it stops a pod, and the program should finish the requests it has already accepted instead of dropping them. And it pulls the image onto every node that runs it, so the image should be small and contain nothing an attacker could use. You will build all three here, then package Snip on a distroless base image, which holds no shell or package manager, only your binary and a few files it needs.

The project lives in ~/snip-demo. Every later part of the series builds on it, so keep the folder, the image and the kind cluster when you finish.

Step 1 · Create the Snip module

Make the project folder, start a Go module and add pgx, the PostgreSQL driver Snip uses. pgx is written in pure Go, which matters later: a static binary needs no C libraries.

Bash
mkdir -p ~/snip-demo
cd ~/snip-demo
go mod init example.com/snip
go get github.com/jackc/pgx/v5@v5.13.0

Check it worked

go mod init prints go: creating new go.mod: module example.com/snip. go get downloads pgx and prints go: added github.com/jackc/pgx/v5 v5.13.0 along with a few lines for its own dependencies. cat go.mod shows the module line, a go line such as go 1.26.0 and a require line for pgx. Since Go 1.26, go mod init writes the previous minor version by default so the module also builds on the older supported release; that is expected, and the Go 1.27.4 toolchain still builds it.

Step 2 · Write the link store

Snip's handlers talk to a Store interface. Two types implement it: memStore, a map guarded by a mutex, and pgStore, which uses database/sql with the pgx driver. The handlers never know which one they have. Create store.go:

Bash
cat > store.go <<'GO'
package main

import (
	"context"
	"database/sql"
	"errors"
	"sync"

	_ "github.com/jackc/pgx/v5/stdlib"
)

// Link is one short code and the address it points to.
type Link struct {
	Code string `json:"code"`
	URL  string `json:"url"`
}

var (
	errNotFound = errors.New("link not found")
	errExists   = errors.New("code already taken")
)

// Store is what the handlers need. Two implementations follow.
type Store interface {
	Create(ctx context.Context, l Link) error
	Get(ctx context.Context, code string) (string, error)
	List(ctx context.Context) ([]Link, error)
	Ping(ctx context.Context) error
}

// memStore keeps links in memory. It is lost when the process stops.
type memStore struct {
	mu    sync.RWMutex
	urls  map[string]string
	order []string
}

func newMemStore() *memStore { return &memStore{urls: map[string]string{}} }

func (m *memStore) Create(_ context.Context, l Link) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	if _, ok := m.urls[l.Code]; ok {
		return errExists
	}
	m.urls[l.Code] = l.URL
	m.order = append(m.order, l.Code)
	return nil
}

func (m *memStore) Get(_ context.Context, code string) (string, error) {
	m.mu.RLock()
	defer m.mu.RUnlock()
	u, ok := m.urls[code]
	if !ok {
		return "", errNotFound
	}
	return u, nil
}

func (m *memStore) List(_ context.Context) ([]Link, error) {
	m.mu.RLock()
	defer m.mu.RUnlock()
	links := make([]Link, 0, len(m.order))
	for _, c := range m.order {
		links = append(links, Link{Code: c, URL: m.urls[c]})
	}
	return links, nil
}

func (m *memStore) Ping(context.Context) error { return nil }

// pgStore keeps links in PostgreSQL through the pgx driver.
type pgStore struct{ db *sql.DB }

const schema = `CREATE TABLE IF NOT EXISTS links (
	code       text PRIMARY KEY,
	url        text NOT NULL,
	created_at timestamptz NOT NULL DEFAULT now()
)`

func openPGStore(dsn string) (*pgStore, error) {
	db, err := sql.Open("pgx", dsn)
	if err != nil {
		return nil, err
	}
	db.SetMaxOpenConns(10)
	return &pgStore{db: db}, nil
}

func (p *pgStore) Migrate(ctx context.Context) error {
	_, err := p.db.ExecContext(ctx, schema)
	return err
}

func (p *pgStore) Create(ctx context.Context, l Link) error {
	res, err := p.db.ExecContext(ctx,
		`INSERT INTO links (code, url) VALUES ($1, $2) ON CONFLICT (code) DO NOTHING`, l.Code, l.URL)
	if err != nil {
		return err
	}
	if n, _ := res.RowsAffected(); n == 0 {
		return errExists
	}
	return nil
}

func (p *pgStore) Get(ctx context.Context, code string) (string, error) {
	var u string
	err := p.db.QueryRowContext(ctx, `SELECT url FROM links WHERE code = $1`, code).Scan(&u)
	if errors.Is(err, sql.ErrNoRows) {
		return "", errNotFound
	}
	return u, err
}

func (p *pgStore) List(ctx context.Context) ([]Link, error) {
	rows, err := p.db.QueryContext(ctx, `SELECT code, url FROM links ORDER BY created_at, code`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	links := []Link{}
	for rows.Next() {
		var l Link
		if err := rows.Scan(&l.Code, &l.URL); err != nil {
			return nil, err
		}
		links = append(links, l)
	}
	return links, rows.Err()
}

func (p *pgStore) Ping(ctx context.Context) error { return p.db.PingContext(ctx) }
GO

A few choices in this file matter for later parts:

  • Ping is what readiness will use. The memory store is always ready; the PostgreSQL store is ready only when the database answers.
  • ON CONFLICT (code) DO NOTHING turns a clash between two random codes into errExists, which the handler retries, instead of a database error.
  • Migrate creates the table. In part 3 a Kubernetes Job runs it once, before the API starts, through the migrate subcommand you add in a later step.

Now let Go record the exact dependency versions the code uses:

Bash
go mod tidy

Check it worked

go mod tidy exits without output, or prints a few go: downloading lines. go.sum now exists, and go.mod lists github.com/jackc/pgx/v5 v5.13.0 in its first require block, with packages such as github.com/jackc/puddle/v2 marked // indirect.

Step 3 · Add the API and the health endpoints

Create handlers.go. It has five routes: create a link, list links, follow a link, and the two health endpoints:

Bash
cat > handlers.go <<'GO'
package main

import (
	"context"
	"crypto/rand"
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"net/url"
	"sync/atomic"
	"time"
)

type app struct {
	store    Store
	draining atomic.Bool // true once shutdown has started
}

func (a *app) routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /healthz", a.healthz)
	mux.HandleFunc("GET /readyz", a.readyz)
	mux.HandleFunc("POST /links", a.createLink)
	mux.HandleFunc("GET /links", a.listLinks)
	mux.HandleFunc("GET /{code}", a.follow)
	return mux
}

// healthz answers "is the process alive?" It checks nothing else.
func (a *app) healthz(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("ok\n"))
}

// readyz answers "should this copy get traffic now?"
func (a *app) readyz(w http.ResponseWriter, r *http.Request) {
	if a.draining.Load() {
		http.Error(w, "draining", http.StatusServiceUnavailable)
		return
	}
	ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
	defer cancel()
	if err := a.store.Ping(ctx); err != nil {
		log.Printf("readyz: store: %v", err)
		http.Error(w, "store unavailable", http.StatusServiceUnavailable)
		return
	}
	w.Write([]byte("ready\n"))
}

func (a *app) createLink(w http.ResponseWriter, r *http.Request) {
	var in struct {
		URL string `json:"url"`
	}
	r.Body = http.MaxBytesReader(w, r.Body, 4096)
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		http.Error(w, "body must be JSON like {\"url\":\"https://...\"}", http.StatusBadRequest)
		return
	}
	u, err := url.Parse(in.URL)
	if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
		http.Error(w, "url must be an absolute http or https address", http.StatusBadRequest)
		return
	}
	for range 3 {
		l := Link{Code: newCode(), URL: u.String()}
		err = a.store.Create(r.Context(), l)
		if errors.Is(err, errExists) {
			continue
		}
		if err != nil {
			log.Printf("create: %v", err)
			http.Error(w, "could not save the link", http.StatusInternalServerError)
			return
		}
		writeJSON(w, http.StatusCreated, l)
		return
	}
	http.Error(w, "could not find a free code, try again", http.StatusServiceUnavailable)
}

func (a *app) listLinks(w http.ResponseWriter, r *http.Request) {
	links, err := a.store.List(r.Context())
	if err != nil {
		log.Printf("list: %v", err)
		http.Error(w, "could not list links", http.StatusInternalServerError)
		return
	}
	writeJSON(w, http.StatusOK, links)
}

func (a *app) follow(w http.ResponseWriter, r *http.Request) {
	target, err := a.store.Get(r.Context(), r.PathValue("code"))
	if errors.Is(err, errNotFound) {
		http.NotFound(w, r)
		return
	}
	if err != nil {
		log.Printf("follow: %v", err)
		http.Error(w, "could not look up the link", http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, target, http.StatusFound)
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	json.NewEncoder(w).Encode(v)
}

// newCode returns six characters without look-alikes such as 0/o and 1/l.
func newCode() string {
	const alphabet = "abcdefghijkmnpqrstuvwxyz23456789"
	b := make([]byte, 6)
	rand.Read(b)
	for i := range b {
		b[i] = alphabet[int(b[i])%len(alphabet)]
	}
	return string(b)
}
GO

The two health endpoints answer different questions, and part 4 depends on keeping them apart:

  • /healthz (liveness) only proves the process can answer HTTP. It must not check the database. If PostgreSQL goes down and liveness fails, Kubernetes restarts every Snip pod at once, which fixes nothing and adds load just as the database comes back.
  • /readyz (readiness) says whether this copy should get new requests. It fails when the store cannot be reached, and a failing readiness check takes the pod out of the Service's list of endpoints without restarting it. It also answers 503 once shutdown has started, through the draining flag, but that is a safeguard rather than the way a stopping pod leaves the Service: Kubernetes marks a terminating pod not ready in its EndpointSlice whatever the probe says, and the next step closes the listener as soon as shutdown begins, so a probe on a new connection cannot connect at all. The flag only matters to a request that arrives on a keep-alive connection that is still open.

GET /{code} matches any single path segment, but the router prefers the more specific GET /links, GET /healthz and GET /readyz, so those three never reach follow.

Check it worked

Run gofmt -l .. It prints no file names when store.go and handlers.go are formatted as Go expects, and a syntax error message if a paste went wrong. Do not run go vet or go build yet: the package has no main function until the next step.

Step 4 · Shut down cleanly on SIGTERM

When Kubernetes stops a pod, during a rollout, a scale-down or a node drain, it sends SIGTERM to the container's main process, waits for the grace period (30 seconds unless you change terminationGracePeriodSeconds) and then sends SIGKILL. A Go program that does nothing special exits at once on SIGTERM and drops any request that is half done. Create main.go so that Snip instead sets its draining flag, stops accepting new connections and lets running requests finish:

Bash
cat > main.go <<'GO'
package main

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

func main() {
	if len(os.Args) > 1 && os.Args[1] == "migrate" {
		if err := migrate(); err != nil {
			log.Fatalf("migrate: %v", err)
		}
		log.Print("migrate: schema is up to date")
		return
	}
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	// SIGTERM is what Kubernetes sends; os.Interrupt is Ctrl+C.
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
	defer stop()

	a := &app{store: newMemStore()}
	if dsn := os.Getenv("DATABASE_URL"); dsn != "" {
		pg, err := openPGStore(dsn)
		if err != nil {
			return err
		}
		defer pg.db.Close()
		a.store = pg
		log.Print("store: postgresql")
	} else {
		log.Print("store: in memory (set DATABASE_URL to use PostgreSQL)")
	}

	addr := os.Getenv("ADDR")
	if addr == "" {
		addr = ":8080"
	}
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	srv := &http.Server{
		Handler:           a.routes(),
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       10 * time.Second,
		WriteTimeout:      10 * time.Second,
		IdleTimeout:       60 * time.Second,
	}
	log.Printf("listening on %s", ln.Addr())
	return serve(ctx, srv, ln, &a.draining)
}

// serve runs srv until ctx is cancelled, then stops taking new connections
// and gives requests already in flight up to 20 seconds to finish.
func serve(ctx context.Context, srv *http.Server, ln net.Listener, draining *atomic.Bool) error {
	errc := make(chan error, 1)
	go func() { errc <- srv.Serve(ln) }()

	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
	}

	draining.Store(true)
	log.Print("shutting down: finishing in-flight requests")
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil {
		return err
	}
	log.Print("stopped")
	return nil
}

func migrate() error {
	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		log.Fatal("migrate: DATABASE_URL is not set")
	}
	pg, err := openPGStore(dsn)
	if err != nil {
		return err
	}
	defer pg.db.Close()
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	return pg.Migrate(ctx)
}
GO

How the pieces fit:

  • signal.NotifyContext returns a context that is cancelled when SIGTERM or Ctrl+C arrives. Catching the signal also stops Go's default behaviour of exiting immediately.
  • serve takes a listener instead of an address so that the test in the next step can run it on a random free port.
  • srv.Shutdown closes the listener, closes idle keep-alive connections and waits for active requests to finish. The 20-second limit stays inside Kubernetes' default 30-second grace period, so Snip exits on its own before the SIGKILL.
  • Closing the listener straight away leaves a gap. Removing a terminating pod from the Service's endpoints takes a moment to reach every node and proxy, and a new request sent in that moment is refused rather than served. Part 4 closes the gap with a short preStop pause, so Snip keeps serving until traffic has moved away before it receives SIGTERM.
  • ADDR defaults to :8080, every interface, which is what a container needs. Configuration comes only from environment variables, so nothing secret is baked into the image: part 3 passes DATABASE_URL from a Kubernetes Secret.

Check it worked

Bash
go vet ./...

go vet prints nothing and exits with status 0. Run gofmt -l . as well; it prints no file names if the code is formatted as Go expects.

Step 5 · Test the handlers and the drain

The handler tests use httptest and need no port. The last test is the important one for Kubernetes: it starts a request that takes half a second, cancels the context the way SIGTERM does, and checks that the request still completes, that serve returns cleanly, and that new connections are refused afterwards. Create snip_test.go:

Bash
cat > snip_test.go <<'GO'
package main

import (
	"context"
	"encoding/json"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync/atomic"
	"testing"
	"time"
)

func do(t *testing.T, h http.Handler, method, path, body string) *httptest.ResponseRecorder {
	t.Helper()
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body)))
	return rec
}

func TestCreateFollowList(t *testing.T) {
	h := (&app{store: newMemStore()}).routes()

	rec := do(t, h, "POST", "/links", `{"url":"https://example.com/docs"}`)
	if rec.Code != http.StatusCreated {
		t.Fatalf("create: got %d %q", rec.Code, rec.Body)
	}
	var l Link
	if err := json.Unmarshal(rec.Body.Bytes(), &l); err != nil || len(l.Code) != 6 {
		t.Fatalf("create: bad body %q", rec.Body)
	}

	rec = do(t, h, "GET", "/"+l.Code, "")
	if rec.Code != http.StatusFound || rec.Header().Get("Location") != "https://example.com/docs" {
		t.Fatalf("follow: got %d to %q", rec.Code, rec.Header().Get("Location"))
	}

	rec = do(t, h, "GET", "/links", "")
	if !strings.Contains(rec.Body.String(), l.Code) {
		t.Fatalf("list: %q does not contain %s", rec.Body, l.Code)
	}
}

func TestRejectsBadInput(t *testing.T) {
	h := (&app{store: newMemStore()}).routes()
	for _, body := range []string{`not json`, `{"url":"ftp://example.com"}`, `{"url":"/relative"}`} {
		if rec := do(t, h, "POST", "/links", body); rec.Code != http.StatusBadRequest {
			t.Errorf("body %s: got %d, want 400", body, rec.Code)
		}
	}
	if rec := do(t, h, "GET", "/nosuch", ""); rec.Code != http.StatusNotFound {
		t.Errorf("unknown code: got %d, want 404", rec.Code)
	}
}

func TestHealthAndReadiness(t *testing.T) {
	a := &app{store: newMemStore()}
	h := a.routes()
	if rec := do(t, h, "GET", "/healthz", ""); rec.Code != http.StatusOK {
		t.Fatalf("healthz: got %d", rec.Code)
	}
	if rec := do(t, h, "GET", "/readyz", ""); rec.Code != http.StatusOK {
		t.Fatalf("readyz: got %d", rec.Code)
	}
	a.draining.Store(true)
	if rec := do(t, h, "GET", "/readyz", ""); rec.Code != http.StatusServiceUnavailable {
		t.Fatalf("readyz while draining: got %d, want 503", rec.Code)
	}
	if rec := do(t, h, "GET", "/healthz", ""); rec.Code != http.StatusOK {
		t.Fatalf("healthz while draining: got %d, want 200", rec.Code)
	}
}

// TestShutdownDrainsInFlightRequest starts a slow request, then cancels the
// context the way SIGTERM does in run, and checks the request still finishes.
func TestShutdownDrainsInFlightRequest(t *testing.T) {
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	started := make(chan struct{})
	srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		close(started)
		time.Sleep(500 * time.Millisecond)
		io.WriteString(w, "finished")
	})}

	var draining atomic.Bool
	ctx, cancel := context.WithCancel(context.Background())
	served := make(chan error, 1)
	go func() { served <- serve(ctx, srv, ln, &draining) }()

	body := make(chan string, 1)
	go func() {
		resp, err := http.Get("http://" + ln.Addr().String() + "/slow")
		if err != nil {
			body <- "error: " + err.Error()
			return
		}
		defer resp.Body.Close()
		b, _ := io.ReadAll(resp.Body)
		body <- string(b)
	}()

	<-started
	cancel()

	if got := <-body; got != "finished" {
		t.Fatalf("in-flight request: got %q, want %q", got, "finished")
	}
	if err := <-served; err != nil {
		t.Fatalf("serve returned %v, want nil", err)
	}
	if !draining.Load() {
		t.Fatal("draining flag was not set")
	}
	if _, err := http.Get("http://" + ln.Addr().String() + "/"); err == nil {
		t.Fatal("server still accepts new connections after shutdown")
	}
}
GO

Run the tests with -v to see each one:

Bash
go test -count=1 -v ./...

Check it worked

Four tests report --- PASS: TestCreateFollowList, TestRejectsBadInput, TestHealthAndReadiness and TestShutdownDrainsInFlightRequest. The drain test prints the two log lines shutting down: finishing in-flight requests and stopped and takes a little over half a second. The output ends with ok example.com/snip. -count=1 makes Go run the tests again instead of reusing a cached result.

Step 6 · Build a static binary and try it

Build Snip the way the Dockerfile will. CGO_ENABLED=0 makes the Go toolchain produce a binary that links no C libraries, so it runs on a base image without libc; without cgo, Go also uses its own DNS resolver. -trimpath removes the paths of your machine from the binary, so two builds of the same code on different machines match and no home folder names leak into it. -ldflags="-s -w" drops the symbol table and debug information, which makes the file smaller.

Bash
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o snip .
go version -m ./snip | grep -E 'CGO_ENABLED|trimpath'
ls -lh snip

go version -m reads the build settings Go stores in every binary. Start Snip in the background on the loopback address, with its log written to snip.log:

Bash
ADDR=127.0.0.1:8080 ./snip 2> snip.log &

Ask both health endpoints, create a link, follow it and list all links:

Bash
curl -s http://127.0.0.1:8080/healthz
curl -s http://127.0.0.1:8080/readyz
curl -s -X POST -H 'Content-Type: application/json' -d '{"url":"https://go.dev/doc/"}' http://127.0.0.1:8080/links | tee link.json
CODE=$(sed -E 's/.*"code":"([a-z0-9]+)".*/\1/' link.json)
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' "http://127.0.0.1:8080/$CODE"
curl -s http://127.0.0.1:8080/links

Now send the same signal Kubernetes would, and read the log:

Bash
kill -TERM %1
wait %1
echo "snip exited with status $?"
cat snip.log

Check it worked

go version -m prints build -trimpath=true and build CGO_ENABLED=0, and the binary is about 10 MB. The health endpoints print ok and ready. The POST prints something like {"code":"k7mq2x","url":"https://go.dev/doc/"}, following the code prints 302 https://go.dev/doc/, and the list is a JSON array holding that one link. After kill, the shell prints snip exited with status 0, and snip.log ends with shutting down: finishing in-flight requests and stopped. Remove the two scratch files with rm link.json snip.log.

The links are gone now, because the memory store lives only as long as the process. That is fine for this part; part 3 adds PostgreSQL.

Step 7 · Write a two-stage Dockerfile on distroless

The build stage has the full Go toolchain, several hundred megabytes, and is thrown away. The runtime stage starts from gcr.io/distroless/static-debian13:nonroot, which contains CA certificates, time zone data, a /tmp folder and an /etc/passwd with a nonroot user (UID 65532), and nothing else: no shell, no apt, no curl. If someone does find a way to run commands inside the container, there are almost no tools there to use.

Keep build output and local files out of the build context first:

Bash
cat > .dockerignore <<'IGNORE'
snip
*.log
*.json
.git
.env
.env.*
IGNORE

Then the Dockerfile:

Bash
cat > Dockerfile <<'DOCKER'
# Build stage: the Go toolchain. Never shipped.
FROM golang:1.27.4-trixie AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY *.go ./
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/snip .

# Runtime stage: Snip, CA certificates and tzdata. No shell.
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/snip /snip
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/snip"]
DOCKER

Line by line, the parts that matter:

  • Copying go.mod and go.sum before the source means go mod download is cached as its own layer. Changing a .go file rebuilds from the COPY *.go line, without downloading modules again.
  • The build tag 1.27.4-trixie pins both the Go patch release and Debian 13, the same Debian release the runtime image is built from.
  • USER 65532:65532 repeats, as numbers, what the nonroot tag already sets. Kubernetes' runAsNonRoot: true (part 7) can only confirm that a user is not root when the image names it by number; with a user name it refuses to start the pod.
  • ENTRYPOINT ["/snip"] is the exec form, so Snip is process 1 in the container and receives SIGTERM directly. The shell form (ENTRYPOINT /snip) would need /bin/sh, which distroless does not have, and a shell in front of your program does not pass signals on.

Build the image. The first build downloads both base images, so it takes a few minutes; later builds take seconds:

Bash
docker build -t snip:0.1.0 .
docker image ls snip
docker image inspect snip:0.1.0 --format '{{.Config.User}} {{json .Config.Entrypoint}}'

A note if you push images over mobile or prepaid data: the image built here is around 15 MB, about the size of a few phone photos, while an image based on the full golang image would be close to a gigabyte. Every node in the cluster pulls it, and so does every CI run that does not cache it.

Check it worked

docker image ls snip lists snip with tag 0.1.0 and a size of about 12 to 15 MB: the binary plus 2 MB or so of distroless. docker image inspect prints 65532:65532 ["/snip"].

Step 8 · Run the image and confirm what is missing

Run the container on a different local port, check it, then stop it the way Docker does, with SIGTERM:

Bash
docker run -d --name snip-try -p 127.0.0.1:8081:8080 snip:0.1.0
curl -s http://127.0.0.1:8081/readyz
docker run --rm --entrypoint sh snip:0.1.0
docker stop snip-try
docker logs snip-try
docker rm snip-try

Check it worked

curl prints ready. The --entrypoint sh attempt fails with an error containing exec: "sh": executable file not found in $PATH: there is no shell to open. docker stop returns in well under a second, not after its 10-second timeout, and docker logs shows store: in memory ..., a line like listening on [::]:8080, shutting down: finishing in-flight requests and stopped. The last two lines prove the signal reached Snip inside the container.

Because there is no shell, docker exec -it snip-try sh will never work on this image. To inspect a running pod in Kubernetes you attach a separate debugging container with kubectl debug, covered in /tutorials/debug-a-failing-kubernetes-pod-with-kubectl.

Step 9 · Load the image into kind

Create the cluster the series uses. It is called snip, so it sits beside any other kind clusters you have. If you deleted the cluster from /tutorials/run-your-first-kubernetes-cluster-with-kind, this is the same command with a different name:

Bash
kind create cluster --name snip --image kindest/node:v1.37.0 --wait 120s
kind load docker-image snip:0.1.0 --name snip
docker exec snip-control-plane crictl images | grep snip

The kind node cannot see your local Docker images, so kind load docker-image copies the image into it. Start one short-lived pod from it to prove it runs there. --image-pull-policy=Never stops the node from looking for snip:0.1.0 in a registry:

Bash
kubectl --context kind-snip run snip-try --image=snip:0.1.0 --image-pull-policy=Never --port=8080
kubectl --context kind-snip wait --for=condition=Ready pod/snip-try --timeout=60s
kubectl --context kind-snip logs snip-try
kubectl --context kind-snip delete pod snip-try

A pod's logs go with it, so read them before you delete it. You will watch the drain during a live rollout in part 4.

Check it worked

crictl images lists docker.io/library/snip with tag 0.1.0. The pod reaches condition met, and its log shows store: in memory (set DATABASE_URL to use PostgreSQL) and a line like listening on [::]:8080. kubectl delete pod waits a moment and prints pod "snip-try" deleted; it does not take the full 30-second grace period, because Snip exits as soon as it has drained.

Keep the snip cluster, the snip:0.1.0 image and ~/snip-demo. Part 2 deploys this image with Kustomize, and the series clean-up comes in part 8.

Next steps

  • Compare this with a multi-stage build for a Node.js site, where the runtime stage still needs an interpreter: /tutorials/make-docker-images-smaller-multi-stage.
  • Go deeper on Go's HTTP server, timeouts and routing patterns: /tutorials/write-your-first-go-web-server.
  • Revisit kind, kubectl and loading local images: /tutorials/run-your-first-kubernetes-cluster-with-kind.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.