12.2.4.4 Go Cross Compile
A focused guide to Go Cross Compile, connecting core concepts with practical Docker and container operations.
Go cross-compile uses Go's built-in ability to compile a binary targeting a different operating system or CPU architecture than the one currently running the build, useful within a Docker build for producing images targeting an architecture different from the build machine's own.
Cross-Compiling for a Different Target Architecture
Setting the appropriate environment variables before building instructs Go's compiler to target a different architecture.
FROM golang:1.22 AS build
WORKDIR /app
COPY . .
RUN GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -o /app/server .
This produces a binary targeting Linux on ARM64, regardless of the actual architecture the build itself is running on.
Why This Matters for Multi-Architecture Image Builds
Building images that need to support multiple architectures (x86-64 and ARM64, for instance) can leverage this cross-compilation capability without necessarily requiring actual ARM64 hardware to perform the build.
docker buildx build --platform linux/amd64,linux/arm64 -t myapp:1.0 .
Combined with buildx's multi-platform support, Go's cross-compilation capability simplifies producing genuinely multi-architecture images.
Why Cross-Compilation Avoids the Need for Architecture-Specific Build Machines
Without cross-compilation, producing an ARM64 image would typically require either actual ARM64 build hardware or relying on slower architecture emulation — Go's native cross-compilation support sidesteps this need entirely for compiled Go binaries.
time docker buildx build --platform linux/arm64 .
A build using Go's native cross-compilation generally completes considerably faster than one relying on emulated execution for the equivalent target architecture.
Verifying the Resulting Binary's Target Architecture
Confirming the compiled binary actually targets the intended architecture validates the cross-compilation succeeded as expected.
file server
server: ELF 64-bit LSB executable, ARM aarch64
Why Go Cross-Compile Matters
Go's native cross-compilation capability provides a notably efficient way to produce multi-architecture container images, avoiding the overhead that architecture emulation would otherwise introduce for languages without this same straightforward cross-compilation support.