Docker
Beginner
1 min read
Multi-Stage Builds for Go Static Binaries
Example
# Dockerfile - Go application with scratch final stage
# Builder stage
FROM golang:1.22-alpine AS builder
WORKDIR /src
# Download dependencies first (cached layer)
COPY go.mod go.sum ./
RUN go mod download
# Copy source and build static binary
COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build -ldflags="-w -s" -o /bin/server ./cmd/server
# Final stage (scratch = empty filesystem)
FROM scratch AS production
# Copy TLS root certificates (needed for HTTPS outbound calls)
COPY --from=builder /etc/ssl/certs/ca-certificates.crt \
/etc/ssl/certs/
# Copy the static binary only
COPY --from=builder /bin/server /server
# Non-root UID (scratch has no useradd; use numeric UID)
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/server"]
# Builder image: ~340 MB (golang:alpine)
# Production image: ~8 MB (scratch + binary)
# docker build -t mygoapp:latest .
Related Resources
Docker Reference
Complete tag & property list
Docker How-To Guides
Step-by-step practical guides
Docker Exercises
Practice what you've learned
More in Docker