Back to articles
Docker Multi-Stage Builds for Go: From 1GB to 12MB Production Images
How-ToDevOps

Docker Multi-Stage Builds for Go: From 1GB to 12MB Production Images

via Dev.to DevOpsYoung Gao

Docker Multi-Stage Builds for Go: From 1GB to 12MB Production Images Most Go Docker images are built wrong. A typical FROM golang:1.22 image weighs 800MB+. Your compiled Go binary is probably 10-15MB. Here's how to use multi-stage builds to ship minimal, secure images — and avoid the common pitfalls. The Problem # DON'T do this FROM golang:1.22 WORKDIR /app COPY . . RUN go build -o server . CMD ["./server"] This image includes the entire Go toolchain, build cache, and source code. Result: ~850MB image containing ~840MB of stuff you don't need in production. The Basic Multi-Stage Fix # Stage 1: Build FROM golang:1.22-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED = 0 GOOS = linux go build -o server . # Stage 2: Run FROM alpine:3.19 RUN apk --no-cache add ca-certificates COPY --from=builder /app/server /server CMD ["/server"] This gets you to ~20MB. But we can do better, and there are production concerns to address. The Production Docker

Continue reading on Dev.to DevOps

Opens in a new tab

Read Full Article
8 views

Related Articles