By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
This lab produces the Linux artifact from your workstation and packages it into a runtime image with no compiler, no shell and a non-root user. Cross-compilation is the part teams forget until CI fails: a binary built for the wrong architecture starts with exec format error, and a CGO-linked binary built on macOS may not run in a minimal container at all.
Do the build in two phases. First prove the cross-compile locally with go env GOOS GOARCH and a real go build for linux/amd64 and linux/arm64. Then build the image and inspect it: the configured user, the entry point and the fact that the binary is static. A container that runs as root with a full base image undoes most of the security work from step 35.
CGO_ENABLED=0, -trimpath and stripped symbols.file and go version -m to confirm target and module graph.# Prove the cross-compile target without writing a binary.
GOOS=linux GOARCH=arm64 go env GOOS GOARCH# Two-stage image: compiler in the builder, static binary in the runtime.
cat > Dockerfile <<'EOF'
FROM golang:1.23 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build -trimpath -ldflags="-s -w" -o /out/relayd ./cmd/relayd
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/relayd /relayd
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/relayd"]
EOF
# Build, run, and prove the service answers from outside the container.
docker build -t relay:lab .
docker run --rm -d --name relay-lab -p 8080:8080 \
-e RELAY_API_KEY=local-dev-key relay:lab
curl -fsS http://127.0.0.1:8080/healthz
docker stop relay-lab| Check | Command | Expected result |
|---|---|---|
| Target platform | GOOS=linux GOARCH=arm64 go env GOOS GOARCH | linux / arm64 |
| Static binary | file dist/relayd | ELF 64-bit, statically linked |
| Embedded module graph | go version -m dist/relayd | Your module and dependency versions |
| Container user | docker image inspect relay:lab --format '{{.Config.User}}' | nonroot |
| Service health | curl -fsS localhost:8080/healthz | 200 OK |
| Reproducibility | Build twice, compare checksums | Identical checksums with the same flags |
Key takeaways
Cross-compile static Linux binaries with CGO_ENABLED=0, GOOS and GOARCH.
Verify the target with go env and inspect artifacts with file and go version -m.
Use a two-stage Dockerfile with a pinned builder and a minimal non-root runtime.
Copy the module files before the source so dependency layers stay cached.
Run the container and check health from outside before calling the lab complete.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.