Home >Backend Development >Golang >How Can I Manually Fetch Go Dependencies for Faster Docker Builds?
One of the key concepts introduced in Go 1.11 is module support. While the automatic dependency installation feature is usually beneficial, some use cases might require manual dependency fetching.
For example, in a Docker build environment, where dependency changes are far less frequent than code changes, leveraging Docker's layer caching can significantly speed up rebuilds by separating the dependency installation stage from the build stage.
Go now provides a solution to this challenge. Thanks to issue #26610, you can utilize the go mod download command to manually fetch dependencies. This command requires only the presence of the go.mod and go.sum files.
Here's an example of a cached multistage Docker build that employs this technique:
FROM golang:1.17-alpine as builder RUN apk --no-cache add ca-certificates git WORKDIR /build # Fetch dependencies COPY go.mod go.sum ./ RUN go mod download # Build COPY . ./ RUN CGO_ENABLED=0 go build # Create final image FROM alpine WORKDIR / COPY --from=builder /build/myapp . EXPOSE 8080 CMD ["./myapp"]
Additionally, the article "Containerize Your Go Developer Environment – Part 2" provides valuable insights on leveraging the Go compiler cache to further enhance build speeds.
The above is the detailed content of How Can I Manually Fetch Go Dependencies for Faster Docker Builds?. For more information, please follow other related articles on the PHP Chinese website!