When crafting Docker images, the need arises to cache dependencies to expedite the build process. This article tackles the issue of pre-building all required modules and caching them.
One approach involves adding a layer to cache dependencies while building the image. However, this step requires building the dependency, which can be time-consuming. An alternative method is to use the go build command.
Another option is to pre-build all dependencies listed in the go.mod file. Fortunately, Docker provides documentation that addresses this very issue. The suggested approach is to structure the Dockerfile in the following manner:
FROM --platform=${BUILDPLATFORM} docker.io/golang:1.16.7-alpine AS build ARG TARGETOS ARG TARGETARCH WORKDIR /src ENV CGO_ENABLED=0 COPY go.* . RUN go mod download COPY . . RUN --mount=type=cache,target=/root/.cache/go-build \ GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -o /out/example . FROM scratch COPY --from=build /out/example /
Simplified for a single architecture, the relevant caching aspect looks like this:
FROM docker.io/golang:1.16.7-alpine AS build WORKDIR /src COPY go.* . RUN go mod download COPY . . RUN --mount=type=cache,target=/root/.cache/go-build go build -o /out/example . FROM scratch COPY --from=build /out/example /
This mechanism mounts a cache directory on /root/.cache/go-build, which houses the go build cache. During the initial build, the cache is populated. Subsequent builds will leverage the cached files.
To activate this functionality, include DOCKER_BUILDKIT=1 when building the image using the docker build command, or use docker buildx. Tests have confirmed the efficacy of this approach.
The above is the detailed content of How to Effectively Cache Dependencies in Docker Images for Golang Projects?. For more information, please follow other related articles on the PHP Chinese website!