Home > Backend Development > Golang > How to Effectively Cache Dependencies in Docker Images for Golang Projects?

How to Effectively Cache Dependencies in Docker Images for Golang Projects?

Susan Sarandon
Release: 2024-10-27 00:51:02
Original
533 people have browsed it

How to Effectively Cache Dependencies in Docker Images for Golang Projects?

Pre-building and Caching Dependencies in Docker Images

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 /
Copy after login

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 /
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template