Skip to content

Instantly share code, notes, and snippets.

@bored-engineer
Last active May 4, 2024 17:41
Show Gist options
  • Save bored-engineer/07cc807daeec407689c1d6b3c3dcf086 to your computer and use it in GitHub Desktop.
Save bored-engineer/07cc807daeec407689c1d6b3c3dcf086 to your computer and use it in GitHub Desktop.
Dockerfile for buliding a simple Golang application with correct caching logic for optimal build performance
# It is faster to cross-compile if the application can be built without CGO
FROM --platform=${BUILDPLATFORM} cgr.dev/chainguard/go:latest as builder
# Building from / or a directory in GOPATH can cause problems
WORKDIR /build
# Fetch the Golang dependencies
RUN --mount=type=cache,target=/go/pkg \
--mount=type=bind,source=go.sum,target=go.sum \
--mount=type=bind,source=go.mod,target=go.mod \
go mod download && go mod verify
# Copy only the Golang source code into the builder
COPY *.go /build/
# Cross-compile, using the cached packages and caching the build artifacts
ARG TARGETOS
ARG TARGETARCH
RUN --mount=type=cache,target=/go/pkg \
--mount=type=cache,target=/root/.cache/go-build \
--mount=type=bind,source=go.sum,target=go.sum \
--mount=type=bind,source=go.mod,target=go.mod \
GOOS=${TARGETOS} GOARCH=${TARGETARCH} CGO_ENABLED=0 go build -o /app .
# The final build layer
FROM cgr.dev/chainguard/static:latest
COPY --from=builder /app /app
ENTRYPOINT ["/app"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment