Last active
May 4, 2024 17:41
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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