123DevOps··8 min read

Go for DevOps: why Kubernetes, Docker, and Terraform were written in Go — and your first CLI

Learn what makes Go the language of choice for infrastructure tooling — a single binary, cross-compilation, concurrency, and a strong standard library — and build a real health check CLI, from go mod init to a distroless image.

Development

Open the repository of almost any tool you use day to day in infrastructure — kubectl, the Docker daemon, terraform, Prometheus, helm — and you will find .go files. That is no coincidence: Go is very good at solving the problems of anyone writing tools that must run on different machines, talk to APIs all the time, and be easy to distribute.

In this article, we look at why Go became the “official language” of the cloud native world and then, hands-on, write a small but useful CLI: a URL health checker that runs its checks in parallel and returns a non-zero exit code when something fails — perfect for scripts and pipelines.

Why Go fits infrastructure tooling

Go was created at Google and announced in 2009, with version 1.0 released in 2012. The idea was always pragmatic: a simple, compiled, garbage-collected language with built-in concurrency, designed for server software maintained by large teams. Those choices match almost perfectly what you expect from a DevOps tool.

Feature What it means in practice
Single static binary scp the executable and you are done: no runtime, no pip install, no node_modules
Cross-compilation with GOOS/GOARCH From your Mac you build binaries for Linux, Windows, ARM, and more with one environment variable
Fast startup No virtual machine to warm up; great for CLIs and short-lived jobs
Goroutines and channels Lightweight, native concurrency for talking to many APIs at once
Strong standard library net/http, encoding/json, crypto/tls, flag, os/exec cover a lot without dependencies
gofmt and official tooling All Go code shares the same formatting; go vet, go test, and go build ship with the install

Two points deserve attention. The first is distribution: a Python or Node tool requires the right interpreter on the target machine; with Go, you ship one file. That simplifies container images, releases, and installs on legacy servers. The second is concurrency: a goroutine is a function that runs concurrently, managed by Go’s own runtime, and it is so cheap that creating thousands of them is normal. For a Kubernetes controller that watches resources all the time, or an exporter that queries dozens of targets, that is gold.

If you are still deciding which language to learn, see also our comparison of programming languages for DevOps.

Well-known tools written in Go

Project What it does
Kubernetes Container orchestration (see how Kubernetes works)
Docker Engine (Moby) and containerd Running and managing containers
etcd Distributed key-value store that holds Kubernetes state
Terraform Infrastructure as code
Prometheus Metrics collection and querying
Grafana (backend) Dashboard server; the frontend is TypeScript
Helm Kubernetes package manager
Hugo Static site generator

A direct consequence: learning Go lets you read the source code of the tools you operate. When something odd happens in production, that is a huge advantage.

Installing Go and creating the project

Download the official installer from go.dev/dl or use your system’s package manager (for example, brew install go on macOS). Then verify the install and create the module:

go version
mkdir healthcheck && cd healthcheck
go mod init github.com/your-org/healthcheck

go mod init creates the go.mod file, which identifies the module and the Go version in use. Our example uses only the standard library, so there will be no external dependencies.

Your first CLI: a concurrent health check

The tool takes a list of URLs, sends a GET to each one at the same time, honors a configurable timeout, and exits with code 1 if any URL fails. Create the main.go file:

package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"
	"sync"
	"time"
)

// result holds the outcome of checking a single URL.
type result struct {
	url      string
	status   int
	duration time.Duration
	err      error
}

func check(client *http.Client, url string) result {
	start := time.Now()
	resp, err := client.Get(url)
	if err != nil {
		return result{url: url, err: err, duration: time.Since(start)}
	}
	defer resp.Body.Close()
	return result{url: url, status: resp.StatusCode, duration: time.Since(start)}
}

func main() {
	timeout := flag.Duration("timeout", 5*time.Second, "maximum time per request")
	flag.Parse()

	urls := flag.Args()
	if len(urls) == 0 {
		fmt.Fprintln(os.Stderr, "usage: healthcheck [-timeout 5s] URL [URL...]")
		os.Exit(2)
	}

	client := &http.Client{Timeout: *timeout}
	results := make([]result, len(urls))

	var wg sync.WaitGroup
	for i, url := range urls {
		wg.Add(1)
		go func() {
			defer wg.Done()
			results[i] = check(client, url) // each goroutine writes only to its own index
		}()
	}
	wg.Wait()

	failures := 0
	for _, r := range results {
		switch {
		case r.err != nil:
			failures++
			fmt.Printf("FAIL %-35s error: %v\n", r.url, r.err)
		case r.status >= 400:
			failures++
			fmt.Printf("FAIL %-35s HTTP %d in %s\n", r.url, r.status, r.duration.Round(time.Millisecond))
		default:
			fmt.Printf("OK   %-35s HTTP %d in %s\n", r.url, r.status, r.duration.Round(time.Millisecond))
		}
	}

	if failures > 0 {
		fmt.Fprintf(os.Stderr, "%d of %d URLs have problems\n", failures, len(urls))
		os.Exit(1)
	}
}

What is going on:

  • flag is the standard package for command-line options. flag.Duration already understands values like 500ms, 3s, or 1m, and flag.Args() returns whatever is left after the options — here, the URLs.
  • http.Client{Timeout: ...} caps the total time of each request. Never use the default client without a timeout in infrastructure tools: a server that never answers would hang your CLI forever.
  • sync.WaitGroup works like a counter: Add(1) before starting each goroutine, Done() when it finishes, and Wait() blocks until the counter reaches zero.
  • Each goroutine writes to its own slot in the slice, so there is no contention over memory and the output keeps the order of the URLs. Since Go 1.22, for loop variables (i and url) are fresh on every iteration, which is why they are safe to use inside the goroutine.
  • The exit code follows the Unix convention: 0 for success, 1 for failed checks, and 2 for incorrect usage.

Building and cross-compiling

go vet ./...
go build -o healthcheck .
./healthcheck -timeout 3s https://example.com https://api.example.com/healthz
echo $?

# binaries for other platforms, from the same machine
GOOS=linux   GOARCH=amd64 CGO_ENABLED=0 go build -ldflags="-s -w" -o dist/healthcheck-linux-amd64 .
GOOS=linux   GOARCH=arm64 CGO_ENABLED=0 go build -ldflags="-s -w" -o dist/healthcheck-linux-arm64 .
GOOS=windows GOARCH=amd64 go build -o dist/healthcheck.exe .

# list every supported combination
go tool dist list

CGO_ENABLED=0 guarantees a fully static binary that does not depend on the target system’s libc, and -ldflags="-s -w" strips the symbol table and debug info, shrinking the file. The same CLI can then run as a pipeline step, an initContainer, or a cron job.

A minimal image with multi-stage builds

Because the binary is static, the final image does not need a full operating system. We use one stage to compile and another, minimal one just to run — the technique we cover in detail in Docker multi-stage builds. If Docker is still new to you, start with what is Docker.

# build stage (use the same Go version declared in go.mod)
FROM golang:1.27 AS build
WORKDIR /src
COPY go.mod ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/healthcheck .

# final stage: no shell, no package manager, non-root user
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/healthcheck /healthcheck
ENTRYPOINT ["/healthcheck"]

The distroless/static image already includes CA certificates and time zone data. If you prefer FROM scratch, remember to copy /etc/ssl/certs/ca-certificates.crt from the build stage; without it, every HTTPS request fails with a certificate error.

Common pitfalls

  • Verbose error handling. The if err != nil { return err } pattern shows up everywhere. That is by design: errors are explicit values. Add context with fmt.Errorf("reading config: %w", err) so the final message says where the problem happened.
  • Goroutine leaks. A goroutine blocked forever — waiting on a channel nobody closes or on a request with no timeout — is never released. Use timeouts, context.Context with cancellation, and make sure every channel has someone on the other end.
  • Unbounded concurrency. Spawning one goroutine per item works for ten URLs, not for a hundred thousand. For large lists, cap parallelism with a fixed-capacity channel used as a semaphore or with a pool of workers.
  • Unclosed response bodies. Forgetting resp.Body.Close() keeps connections open and, over time, exhausts file descriptors.

Next steps

When the CLI grows into several subcommands (healthcheck run, healthcheck config), the cobra package is the de facto standard — the same one used by kubectl, helm, and many others. To automate Kubernetes, the official client-go library gives you access to the cluster API with the same types used by Kubernetes’ own components. And for testing, create *_test.go files and run go test ./...; the net/http/httptest package spins up fake in-memory servers, ideal for testing a tool like ours without depending on the network.

Checklist

  • Go installed and go version working
  • Module created with go mod init and code formatted with gofmt
  • Every HTTP client has a Timeout set
  • Goroutines coordinated with sync.WaitGroup and parallelism capped for large lists
  • Non-zero exit code when the tool detects a failure
  • Binaries built with GOOS/GOARCH and CGO_ENABLED=0
  • Multi-stage final image on distroless or scratch with CA certificates

In DevOps, the best tool is the one you can ship as a single file and that tells you clearly, through its exit code, whether everything is fine.

Get updates on new posts and stay in the loop!