This is specific to Alpine
using the go apk
.
Compiling go binaries in same arch:
go build -buildmode exe -ldflags '-linkmode external -extldflags "-static"' .
Compiling go binaries in other arch:
GOARCH=xxx go build -buildmode exe -ldflags '-linkmode internal -extldflags "-static"' .
It looks like Alpine
[1] force -buildmode pie
by default which doesn't work well for cross compile because of gcc
:
--disable-multilib
where gcc
should include libs for arm64
and x86
families.
You can also pass -w -s
to strip symbols from the binary.
A little word on linkmode
[2][3]:
-linkmode mode
Set link mode (internal, external, auto).
This sets the linking mode as described in cmd/cgo/doc.go.
Sources:
- [1] https://git.alpinelinux.org/cgit/aports/tree/community/go/default-buildmode-pie.patch
- [2] https://golang.org/cmd/link/#hdr-Command_Line
- [3] https://golang.org/src/cmd/cgo/doc.go#L732
- https://groups.google.com/forum/#!topic/golang-nuts/gQ6ArCTlPGU
- https://github.com/golang/go/blob/master/src/cmd/go/internal/work/init.go#L113
- https://stackoverflow.com/questions/40539592/how-to-compile-a-32bit-hello-world-on-alpine
- https://golang.org/cmd/go/
- https://github.com/goreleaser/goreleaser/pull/226/files
- https://stackoverflow.com/questions/36279253/go-compiled-binary-wont-run-in-an-alpine-docker-container-on-ubuntu-host