How to Reduce Go Docker Image Size

Reduce Go Docker image size by using a multi-stage build with a scratch base image to include only the compiled binary.

Use a multi-stage Dockerfile to compile your Go binary in a builder stage and copy only the executable to a minimal runtime image.

# Stage 1: Build
FROM golang:1.23-alpine AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

# Stage 2: Runtime
FROM scratch
COPY --from=builder /app/main .
CMD ["./main"]

This approach strips debug symbols, disables cgo, and uses a scratch base image to eliminate the OS layer entirely.