Building Go with containers.

Build for a particular target

Such as make PLATFORM=darwin/amd64:

FROM --platform=${BUILDPLATFORM} golang:1.16.4-alpine3.13 AS base
WORKDIR /src
ENV CGO_ENABLED=0
COPY go.* .
RUN go mod download
COPY . .

FROM base as build
ARG TARGETOS
ARG TARGETARCH
RUN GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -o /out/server .

FROM base as unit-test
RUN go test -v .

FROM scratch AS bin-unix
COPY --from=build /out/server /

FROM bin-unix AS bin-linux
FROM bin-unix AS bin-darwin

FROM scratch AS bin-windows
COPY --from=build /out/server /server.exe

FROM bin-${TARGETOS} AS bin

Repo: github.com/betandr/congo

Using Multi-stage builds to build a container without Go development dependencies

# syntax=docker/dockerfile:1
FROM golang:1.16 AS builder
WORKDIR /server
COPY . .
COPY ./server .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app ./server

FROM alpine:latest
WORKDIR /root/
COPY --from=builder /server/app .
CMD ["./app"]  

Repo: github.com/betandr/congo