Why I Stopped Using go mod download in My Dockerfile
Using go mod download
inside your Dockerfile can significantly slow down your image build process. Each time you rebuild the image, all Go modules are downloaded again, making the process inefficient, especially during local development when rebuilds are frequent and can take a long time.
While working on the Dockerfile for running my blog inside a Docker container, I encountered this issue firsthand. Every time I made changes and rebuilt the image, Go modules were re-downloaded repeatedly. It quickly became time-consuming and frustrating.
Solution
So, how did I solve this? The answer was simple: I used Docker's build cache. After making the changes, the build times were noticeably reduced, and I could clearly see the improvement.
Dockerfile
With caching (good):
# Set Go proxy to direct (optional)
ENV GOPROXY=direct
# Copy Go mod files and download dependencies
COPY go.mod go.sum ./
# Set cache directories
ENV GOCACHE=/go-cache
ENV GOMODCACHE=/gomod-cache
# Complete other tasks
...
# Build statically linked, optimized binary
RUN --mount=type=cache,target=/gomod-cache --mount=type=cache,target=/go-cache \
go build -o binary main.go
Without caching (bad):
# Copy Go mod files and download dependencies
COPY go.mod go.sum ./
# Download Go modules
RUN go mod download
# Build the Go binary
RUN go build -o binary main.go
# Complete other tasks
...
go mod download
keeps running until it encounters an error or is manually stopped.
You can check out the final Dockerfile here.