Multi-Stage Docker Builds for Go
Builder stage with scratch/alpine final image
Why multi-stage?
A single-stage build that compiles Go code produces a large image with the full Go toolchain. Multi-stage builds compile in one stage and copy only the binary into a minimal final image.
Basic multi-stage Dockerfile
Build stage compiles the binary; final stage copies it into a minimal base:
FROM golang:1.22-alpine AS build
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o myapp ./cmd/server
FROM scratch
COPY --from=build /app/myapp /myapp
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
ENTRYPOINT ["/myapp"]All lessons in this course
- Multi-Stage Docker Builds for Go
- Environment Config and Secrets
- Docker Compose for Local Development
- Health Checks and Production Tuning