Skip to Content
Skip to content
Compile a Static Go Binary Under 10 MB
Beginner
Tutorials

Compile a Static Go Binary Under 10 MB

Compare default go build output against CGO_ENABLED=0 with -trimpath and -ldflags="-s -w", and check shared library links with ldd. After this, you can ship a single small Linux binary anywhere.

Updated 6 min read GoDeployment and Containers

Skip ahead: Already know why static small binaries matter? Jump to Case 1: CGO_ENABLED=0 and -ldflags="-s -w" or Case 5: package into FROM scratch.

A 15-line Go HTTP server compiles to ~8.3 MB by default—and if you ship it naively inside a golang:trixie container, the final Docker image balloons to ~850 MB. Why bother shrinking a binary under 10 MB when modern servers have plenty of disk?

  • Container cold starts and autoscaling: When Kubernetes, Cloud Run, or AWS ECS scales out to a fresh node, it has to pull the container image over the network before the first request can be served. Pulling an 850 MB image takes 15–40 seconds; pulling a 6 MB static binary in FROM scratch takes ~200 milliseconds.
  • Serverless, edge, and CLI distribution limits: AWS Lambda deployment packages, IoT gateways, and CLI tools downloaded thousands of times per hour in CI pipelines pay a direct time and bandwidth tax for every extra megabyte.
  • Smaller CVE and attack surface: A dynamically linked Go binary forces you to ship Debian/Ubuntu glibc, a shell, and OS libraries—dozens of packages that generate weekly security scanner CVEs. A static binary runs in FROM scratch with zero OS packages.

Why a 15-line Go binary starts at 8+ MB

Unlike Python or Node.js scripts that rely on a 100 MB interpreter already installed on the host, Go compiles the entire Go runtime—goroutine scheduler, garbage collector, stack unwinder, and reflection type metadata—directly into every executable, plus full DWARF debug tables for debuggers like delve. That runtime baseline is ~4–5 MB, and DWARF + symbol tables add another ~2.5–3.5 MB on top.

Case 1: default go build vs. CGO_ENABLED=0 -ldflags="-s -w"

Even on a tiny net/http server, a default go build on Linux dynamically links against the host's C library (libc.so.6) so net can call glibc's DNS resolver. That means a binary compiled on Debian/Ubuntu often crashes inside Alpine or FROM scratch with no such file or directory because /lib64/ld-linux-x86-64.so.2 does not exist there.

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "ok")
	})
	http.ListenAndServe(":8080", nil)
}
go build -o ping-default .
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o ping-static .
ls -lh ping-default ping-static
ldd ping-default
ldd ping-static
-rwxr-xr-x 1 root root 8.3M Nov 27 12:13 ping-default
-rwxr-xr-x 1 root root 5.6M Nov 27 12:13 ping-static
	linux-vdso.so.1 (0x00007f77f1db3000)
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f77f1bb6000)
	/lib64/ld-linux-x86-64.so.2 (0x00007f77f1db5000)
	not a dynamic executable

ping-default was 8.3M and tied to the host's glibc. ping-static dropped 32% to 5.6M and ldd confirmed not a dynamic executable—zero shared library dependencies.

Case 2: why net and os/user pull in glibc (and when you still need CGo)

On Linux, Go enables cgo by default for native builds so net (DNS//etc/hosts/NSSwitch) and os/user can call glibc. Setting CGO_ENABLED=0 switches Go to its pure-Go DNS resolver and removes the dynamic linker dependency. When you cannot disable cgo: if your service depends on a C library wrapper (like mattn/go-sqlite3 or image-processing C bindings), CGO_ENABLED=0 will fail to compile—switch to a pure-Go driver (such as modernc.org/sqlite) or ship a Debian/distroless base image.

Case 3: inject build version and commit with -ldflags

Once debug tables are stripped, you still want deployed binaries to report which release and Git commit are running. Combine -s -w with -X to stamp package-level var strings at link time:

package main

import "fmt"

var (
	version = "dev"
	commit  = "none"
)

func main() {
	fmt.Printf("version=%s commit=%s\n", version, commit)
}
go build -trimpath -ldflags="-s -w -X main.version=v1.4.0 -X main.commit=a1b2c3d" -o ver .
./ver
version=v1.4.0 commit=a1b2c3d

Case 4: cross-compile for ARM64 Linux servers

Because CGO_ENABLED=0 removes C compiler dependencies, you can compile an ARM64 binary (for AWS Graviton or Apple Silicon Linux VMs) directly from an x86_64 CI runner without QEMU:

GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o ping-arm64 .
ls -lh ping-arm64
readelf -h ping-arm64 | grep -E "Machine|Class"
-rwxr-xr-x 1 root root 5.2M Nov 27 12:43 ping-arm64
  Class:                             ELF64
  Machine:                           AArch64

Case 5: package it into FROM scratch

FROM golang:trixie AS build
WORKDIR /src
COPY go.mod ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/ping .

FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=build /out/ping /ping
USER 65532:65532
ENTRYPOINT ["/ping"]

💡 Tip: Panic stack traces (file names and line numbers) still work with -ldflags="-s -w" because Go keeps its pclntab runtime table. You only lose interactive delve/gdb debugging—keep an unstripped build artifact in CI if you inspect core dumps.

What each flag does

FlagEffectTrade-off
CGO_ENABLED=0Uses pure-Go DNS/network code instead of libc.so.6Cannot compile packages that depend on C libraries
-trimpathReplaces local developer file paths in stack traces with module pathsReproducible builds across machines
-ldflags="-s -w"Strips symbol table and DWARF debug info (8.3M → 5.6M)Cannot attach delve/gdb to inspect local variables
-X pkg.var=valSets a package-level var string at link timeOnly works on var strings, never const

Common mistakes

  • Forgetting CGO_ENABLED=0 when building on Debian/Ubuntu: the binary runs fine on your laptop, then fails with exec /ping: no such file or directory inside Alpine or scratch because /lib64/ld-linux-x86-64.so.2 is missing.
  • Using shell-form ENTRYPOINT /ping in scratch: shell form tries to run /bin/sh -c /ping, which does not exist in scratch. Always use exec form ENTRYPOINT ["/ping"].
  • Running UPX blindly on Go binaries: UPX can shrink binaries further, but triggers false-positive antivirus alerts on Windows and forces the entire executable to decompress into RAM at startup instead of being demand-paged from disk.

What happens if you skip this

Your CI pipeline ships an 850 MB build image (slowing every deploy and autoscaling event) or builds a dynamically linked binary on Ubuntu that crashes immediately on Alpine/scratch with a cryptic no such file or directory error.

Related course: Go for Beginners.

About

Compare default go build output against CGO_ENABLED=0 with -trimpath and -ldflags="-s -w", and check shared library links with ldd. After this, you can ship a single small Linux binary anywhere.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
6 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.