Reduce Go Binary Size

Always a hot-topic in Go circles is binary size of applications. In this post we will show you how you can reduce the binary size produced from go build for leaner, slimer builds.

In short, adding the ldflags shown below will reduce the size of the binary produced. It does this by removing some perhaps non-critial parts (shouldn’t affect execution, only debugging potentially).

-s Will turn off the symbol table, so you won’t be able to use commands like go tool nm.

-w Turns off the ‘DWARF’ debugging information, so you won’t be able to set breakpoints or get specific information in stacktraces. Likewise, certain profile use cases won’t work, like pprof.

1
go build -ldflags="-s -w"

For example, we’ll take our code from our post about sha3 encoding. If we run the build using Go v1.19 then we get a binary size of 1.8M, but using the ldflags above it will produce a binary size of 1.2M (so a 33% decrease). While this reduction is ground-breaking, it has a bigger impact on larger applications.

How can I check if an application has been stripped?

We can use the same example as above, but use the file command on it. This will tell us if it was stripped of debug information or not.

1
$ go build sha3.go && file sha3
1
2
sha3: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, 
Go BuildID={id}, with debug_info, not stripped

The above is for normal build, notice with debug_info. The below is for a stripped build.

1
$ go build -ldflags="-s -w" sha3.go && file sha3
1
2
sha3: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, 
Go BuildID={id}, stripped

Example In Action

golang reduce binary size

See Other Ways to Reduce Binary Size on Github