Reduce Go Binary Size
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.
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.
The above is for normal build, notice with debug_info. The below is for a stripped build.