Shrink a Go binary
Shrink a Go binary with -ldflags '-s -w', which drops the symbol table and the DWARF debug data. The size on disk falls, and stack traces still work.
A small command line tool compiles to a binary of a few megabytes, and some of that is debugging data you do not ship.
package main
import "fmt"
func main() {
fmt.Println("hello")
}go build -o normal main.go
go build -ldflags '-s -w' -o small main.go
stat -c '%s %n' normal small
./small1822929 normal
1245184 small
helloThe linker flag -s omits the symbol table and -w omits the DWARF information, both listed in the linker documentation. Neither is needed to run the program, so the file is smaller, here from about 1.8 MB to 1.2 MB. A panic in the stripped binary still prints a readable stack trace, because Go keeps its own function tables for the runtime.
A stripped binary cannot be used with gdb or dlv for source level debugging, and profilers lose symbol names, so keep an unstripped build for diagnosing. The saving depends on what the program imports. Compressing with UPX saves more but makes the binary slower to start and is flagged by some scanners.