Docker multi-stage builds for smaller images
Multi-stage builds keep compilation tools out of the final runtime image. These are general examples of the pattern, not measured results from a particular application.
Java/Spring Boot pattern
# Stage 1: Build
FROM maven:3.9-eclipse-temurin-17 AS builder
WORKDIR /app
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn clean package -DskipTests
# Stage 2: Runtime
FROM eclipse-temurin:17-jre-alpine
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
RUN addgroup -S appuser && adduser -S appuser -G appuser
USER appuser
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
The final stage contains the JRE and application artifact rather than Maven, source files and build caches. Image size depends on architecture, tags, dependencies and layers; no fixed saving follows from the Dockerfile alone. The wildcard assumes exactly one runnable JAR in target; select an explicit artifact when the build also creates sources, test or original JARs.
Go pattern
# Stage 1: Build
FROM golang:1-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: Runtime
FROM alpine:latest
RUN apk --no-cache add ca-certificates
RUN addgroup -S appuser && adduser -S appuser -G appuser
WORKDIR /app
COPY --from=builder /app/server .
USER appuser
EXPOSE 8080
CMD ["./server"]
The runtime image excludes the Go compiler and module cache. CGO_ENABLED=0 is appropriate only when the application and its dependencies support a pure-Go build; it is not a universal setting. Alpine also uses musl rather than glibc, which matters for native dependencies.
Layer caching optimization
Order Dockerfile commands by change frequency:
# Dependencies change rarely
COPY pom.xml .
RUN mvn dependency:go-offline
# Source changes often
COPY src ./src
RUN mvn package
This ordering allows the dependency layer to remain reusable when only source files change, provided the relevant build cache is available. It does not guarantee a cache hit on a fresh CI runner.
.dockerignore matters
Don't copy unnecessary files:
.git
target/
*.md
.env
.idea/
node_modules/
Smaller build context = faster builds.
TL;DR
Separate build and runtime stages, run as a non-root user, and keep the build context intentional. Choose the runtime for compatibility and maintenance as well as size; Alpine is an option, not a requirement.
The tags above are illustrative and mutable, including golang:1-alpine and alpine:latest. For reproducible builds, choose reviewed versions/digests and update them deliberately. Record the target platform and compare image sizes and startup behavior on the same application before reporting a saving. See Docker build guidance.