Skip to content

Instantly share code, notes, and snippets.

@marcellodesales
Created August 22, 2019 13:46
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 marcellodesales/fbd7adbe7916c87440cf526ee84a29ba to your computer and use it in GitHub Desktop.
Save marcellodesales/fbd7adbe7916c87440cf526ee84a29ba to your computer and use it in GitHub Desktop.
Cross-compile golang projects in Dockerfile only. Based on https://stackoverflow.com/questions/12168873/cross-compile-go-on-osx/53583797#53583797
############################
# STEP 1 build executable binary
############################
# golang alpine 1.12.6
FROM golang@sha256:cee6f4b901543e8e3f20da3a4f7caac6ea643fd5a46201c3c2387183a332d989 as builder
# Install git + SSL ca certificates.
# Git is required for fetching the dependencies.
# Ca-certificates is required to call HTTPS endpoints.
RUN apk update && apk add --no-cache git ca-certificates tzdata libmagic file && update-ca-certificates
# Create appuser
RUN adduser -D -g '' appuser
WORKDIR $GOPATH/src/mypackage/myapp/
COPY . .
# Fetch dependencies.
RUN go get -d -v
ARG APP_NAME
ENV APP_NAME=${APP_NAME:-hello}
# Build the binary
# https://stackoverflow.com/questions/12168873/cross-compile-go-on-osx/53583797#53583797
RUN for GOOS in darwin linux windows; do for GOARCH in 386 amd64; do output_name="/go/bin/${APP_NAME}-$GOOS-$GOARCH"; if [ $GOOS = "windows" ]; then output_name="${output_name}.exe"; fi; echo "Building $output_name"; CGO_ENABLED=0 GOOS=$GOOS GOARCH=$GOARCH output_name=$output_name go build -ldflags="-w -s" -a -installsuffix cgo -o $output_name; file $output_name; done; done
RUN echo "Preparing runtime image with /go/bin/${APP_NAME}-linux-amd64"
############################
# STEP 2 build a small image
############################
FROM scratch
ARG APP_NAME
# Import from builder.
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /etc/passwd /etc/passwd
# Copy our static executable
COPY --from=builder /go/bin/${APP_NAME}* /go/bin/
COPY --from=builder /go/bin/${APP_NAME}-linux-amd64 /go/bin/app
# Use an unprivileged user.
USER appuser
# Run the hello binary
#ENTRYPOINT ["/go/bin/app"]
CMD ["/go/bin/app"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment