Statically compile Go binaries

$ go build

Sometimes the compiled binary will dynamically link against multiple shared objects.

$ file go-application 
go-application: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically
linked, interpreter /lib64/ld-linux-x86-64.so.2, not stripped
$ ldd go-application 
	linux-vdso.so.1 =>  (0x00007ffd36b63000)
	libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fbda953c000)
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fbda9175000)
	/lib64/ld-linux-x86-64.so.2 (0x000055801e707000)

To avoid this we’ll have to disable CGO.

$ CGO_ENABLED=0 go build

Now the compiled binary will be statically linked against all dependencies and work in environments where glibc is not available like Alpine Linux.

$ file go-application 
go-application: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically
linked, not stripped
$ ldd go-application  
	not a dynamic executable