Skip to content

Instantly share code, notes, and snippets.

@nilium
Last active February 18, 2019 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilium/dd7a58dd9a4d42fba11d65b07d48f15e to your computer and use it in GitHub Desktop.
Save nilium/dd7a58dd9a4d42fba11d65b07d48f15e to your computer and use it in GitHub Desktop.
Dockerfile to cross-compile Go binaries for a target platform and produce a Docker image for the target platform
# Dockerfile to cross-compile Go binaries for a target platform
#
# Usage:
# $ docker build --platform linux/arm .
# Cross-compile package for target platform from build platform
FROM --platform=${BUILDPLATFORM} golang:1-alpine AS build
ADD . /tmp/go
WORKDIR /tmp/go
ARG PACKAGES=.
# TARGETOS and TARGETARCH are set by buildkit
ARG TARGETOS
ARG TARGETARCH
ENV CGO_ENABLED 0
ENV GOOS ${TARGETOS}
ENV GOARCH ${TARGETARCH}
RUN \
for pkg in `go list ${PACKAGES:-.}`; do \
go build -v -o /var/go/bin/`basename $pkg` $pkg; \
done
# Build executable image for target platform
# TARGETPLATFORM is set by buildkit
ARG TARGETPLATFORM
FROM --platform=${TARGETPLATFORM} alpine:3.8
# Copy binaries from build container
COPY --from=build /var/go/bin/* /usr/local/bin/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment