Capstone 3: deploy and shutdown

The last lesson of the course deploys the notes service: three environment variables, a server with the timeouts of lesson 104, a signal that starts the graceful shutdown of lesson 99, and a Dockerfile that builds the static binary. Docker is not in this container, so the image is a sketch and the run below is the binary itself.

Configuration

ADDR is the listen address, DB_FILE selects the file store and is empty for memory, and LOG_LEVEL=debug turns the debug lines on. A default is part of the code, and an empty environment runs the service on a loopback address with a memory store, which is what a developer wants. The environment is read once in main; nothing below it reads os.Getenv.

The server

main builds the store, the API, the root mux and the server, and hands the listener to ListenAndServe in a goroutine. The root mux mounts the API under /api/ and /healthz and the embedded page at /, which is the one-origin design of the last lesson. The four timeouts are set explicitly, and ErrServerClosed is not an error.

package main import ( "context" "errors" "log/slog" "net/http" "os" "os/signal" "syscall" "time" "example.com/notesapi/internal/api" "example.com/notesapi/internal/store" "example.com/notesapi/internal/web" ) var version = "dev" func main() { addr := env("ADDR", "127.0.0.1:8080") dbFile := env("DB_FILE", "") level := slog.LevelInfo if os.Getenv("LOG_LEVEL") == "debug" { level = slog.LevelDebug } log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: level})) var st store.Store = store.NewMemory() if dbFile != "" { st = store.NewFile(dbFile) } a := api.New(st, log) handler := a.Routes() root := http.NewServeMux() root.Handle("/api/", handler) root.Handle("/healthz", handler) root.Handle("/", web.Handler()) srv := &http.Server{ Addr: addr, Handler: root, ReadHeaderTimeout: 2 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second, } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() errc := make(chan error, 1) go func() { log.Info("listening", "addr", addr, "version", version, "db", dbFile) errc <- srv.ListenAndServe() }() select { case err := <-errc: if err != nil && !errors.Is(err, http.ErrServerClosed) { log.Error("server stopped", "error", err) os.Exit(1) } case <-ctx.Done(): log.Info("shutting down") } shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { log.Error("shutdown", "error", err) os.Exit(1) } } func env(name, fallback string) string { if value := os.Getenv(name); value != "" { return value } return fallback }

The version is a package variable and the release stamps it with -X, the same mechanism as the task command. A log line at start-up prints the version, the address and the store, which is the first line an operator reads when a container restarts.

The shutdown

signal.NotifyContext cancels the context on SIGINT or SIGTERM, the select returns and Shutdown gets five seconds to finish the requests in flight. The process exits 0 when the stop is clean and 1 when it is not. The container runtime sends SIGTERM and kills after its grace period, which is why the five seconds is a decision about the platform, not about Go.

The image

A two-stage build: the Go image compiles a static binary, and a small image carries it. The build sets CGO_ENABLED=0 so the binary needs no libc, and the release flags from the task command. The run stage copies one file, sets ADDR, exposes the port and starts the binary. Docker is not installed in this container, so this file was not built here.

FROM golang:1.26-alpine AS build WORKDIR /src COPY go.mod ./ COPY . . RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=1.0.0" -o /out/notesapi ./cmd/server FROM alpine:3.24 COPY --from=build /out/notesapi /usr/local/bin/notesapi ENV ADDR=:8080 EXPOSE 8080 ENTRYPOINT ["/usr/local/bin/notesapi"]

The image has no shell tools, no source and no static directory: the page is inside the binary. A health check hits /healthz, the logs go to stdout as text, and the file store, when it is used, is a mounted volume. A deployment writes the environment into the platform, not into the image.

A run

The demo reads the same environment with the same defaults, starts the server on a free port, requests the health route and shuts it down. The output shows the configuration, the version and the clean stop.

package main import ( "context" "fmt" "io" "log/slog" "net" "net/http" "os" "time" "example.com/notesapi/internal/api" "example.com/notesapi/internal/store" ) var version = "1.0.0" func env(name, fallback string) string { if value := os.Getenv(name); value != "" { return value } return fallback } func main() { addr := env("ADDR", "127.0.0.1:0") dbFile := env("DB_FILE", "") fmt.Println("addr:", addr) fmt.Println("db file:", dbFile, "(empty means memory)") fmt.Println("version:", version) var st store.Store = store.NewMemory() if dbFile != "" { st = store.NewFile(dbFile) } a := api.New(st, slog.New(slog.NewTextHandler(io.Discard, nil))) handler := a.Routes() root := http.NewServeMux() root.Handle("/api/", handler) root.Handle("/healthz", handler) ln, err := net.Listen("tcp", addr) if err != nil { panic(err) } srv := &http.Server{Handler: root, ReadHeaderTimeout: 2 * time.Second} go srv.Serve(ln) resp, err := http.Get("http://" + ln.Addr().String() + "/healthz") if err != nil { panic(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Println("health:", resp.StatusCode, string(body)) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() fmt.Println("shutdown error:", srv.Shutdown(ctx)) }

go run ./cmd/l135

addr: 127.0.0.1:0
db file: (empty means memory)
version: 1.0.0
health: 200 {"status":"ok"}
shutdown error: <nil>

The empty database path means the memory store, and the health check answered JSON. The shutdown returned with no error, which is the signal the platform reads before it removes the container. A real deployment sets ADDR=:8080, a volume path for DB_FILE and a log level, and the same binary runs.

The end of the course

The course ends with three working projects and the tools to keep them: a JSON library with tests and a benchmark, a task command with storage and a release, and a service with a store, a page, a health check and a shutdown. The language part is not the point any more; the shape of a small Go program is: a package per job, an interface at the seam, errors as values, a test next to the code and a binary that says what it is.

What to read next: the standard library documentation, which is the best-written part of Go, the source of net/http and encoding/json, and the release notes of every version since the one this course ran on. The course index has every lesson; the article groups on the Go hub go further into testing and into Go against C++.

Exercises

  1. Run the demo with ADDR=127.0.0.1:9090 and DB_FILE=/tmp/notes.json. Which lines change, and what does the file contain after a create?
  2. Add a /readyz route that pings the file store. What does it answer before the migration and after, and why is it separate from the health check?
  3. Build the image with the Dockerfile on a machine that has Docker and run it. Which environment variables does the container need, and what does a SIGTERM do to a request in flight?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Where is the configuration read?

    Answer

    Once in main, from the environment

    Nothing below main reads the environment.

  2. What does an empty DB_FILE select?

    Answer

    The memory store

    It is the developer default.

  3. What starts the shutdown?

    Answer

    signal.NotifyContext cancelling on SIGINT or SIGTERM

    The select returns and Shutdown runs.

  4. What does Shutdown wait for?

    Answer

    The requests in flight, with a five-second budget

    The platform kills after its grace period.

  5. Why CGO_ENABLED=0 in the build?

    Answer

    A static binary needs no libc in the run image

    The run stage is small.

  6. What does the run image contain?

    Answer

    The binary, with the page embedded

    One file and the environment.

  7. What does /healthz answer?

    Answer

    A JSON status

    A load balancer and a test read it.

  8. What is the exit status of a clean stop?

    Answer

    0

    The shutdown returned no error.

  9. Why is the Dockerfile a sketch here?

    Answer

    Docker is not installed in the container, so it was not built

    The page says so.

  10. What is the shape of a small Go program?

    Answer

    A package per job, an interface at the seam, errors as values and a test next to the code

    It is what the three capstones build.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev