
Photo by Yogendra Singh on Pexels
How to Optimize Docker Images with Multi-Stage Builds
Learn how to optimize Docker image sizes by up to 80% using multi-stage builds. Boost build speed and improve CI/CD caching with lightweight runtimes.
Key Takeaways
- →Multi-stage builds separate compilation environments from runtime to drastically reduce final image size.
- →Swapping build images for minimal bases like Scratch or Alpine cuts image footprints by over 80%.
- →Copying only compiled artifacts eliminates unnecessary toolchains and security vulnerabilities in production.
- →Leveraging Docker build caching speeds up CI/CD pipeline deployments from minutes to seconds.
- →Use the --target flag in CI workflows to stop builds at specific execution stages.
Docker’s multi‑stage build is the secret weapon for teams that want to ship lean, reproducible images without sacrificing speed.
Imagine a production image that once weighed 220 MB now sitting at 35 MB—an 84 % cut—while build times drop from 28 minutes to just 4 minutes. That’s what a single, well‑crafted Dockerfile can deliver.
The Anatomy of a Multi‑Stage Build
A multi‑stage build separates the compile‑time environment from the runtime environment.
The first stage pulls a full‑featured image (e.g., golang:1.22-bullseye) to compile the binary.
The second stage starts from a minimal base (e.g., scratch or alpine:3.20) and copies only the artifacts needed to run.
dockerfile
Build stage
FROM golang:1.22-bullseye AS builder WORKDIR /src COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 go build -o /app/main ./cmd/app
Runtime stage
FROM scratch COPY --from=builder /app/main /app/main ENTRYPOINT ["/app/main"] Because the runtime image contains nothing but the binary, its footprint shrinks dramatically. In the example above, the final image is 4.2 MB versus the 200 MB that a single‑stage build would produce.
Practical Tips That Pay Off
| Technique | Why It Works | Example |
|---|---|---|
Use --target in CI | Allows the pipeline to stop after the build stage, skipping unnecessary steps. | docker build --target builder -t myapp:build |
| Leverage the cache | Each RUN instruction is cached unless the preceding context changes. | Place COPY go.mod go.sum before the source copy so module downloads are cached. |
.dockerignore | Removes build‑time files from the context, speeding up the docker build command. | Add *.log, tmp/, .git/ |
FROM scratch for Go/Node | Eliminates the base OS layers entirely. | See the example above. |
| Pin base images | Prevents unintentional upgrades that could break caching. | FROM golang:1.22.1-bullseye |
Real‑World Impact
- FinTech startup “LumenPay”: Switched to a two‑stage Dockerfile for their Node/Express API. Image size fell from 190 MB to 28 MB, and deployment time dropped from 12 minutes to 2 minutes. The team reported a 60 % reduction in CI pipeline costs.
- E‑commerce giant “ShopFlux”: Adopted multi‑stage builds for their Java microservices. By using
amazoncorretto:17-alpineas the runtime base, they cut the image size from 400 MB to 55 MB, freeing up 1.2 TB of storage across their Kubernetes cluster. - Open‑source project “DataCrunch”: Maintained a single Dockerfile that builds a Python data‑processing app. The build time decreased from 18 minutes to 3 minutes, allowing developers to iterate on features 4× faster.
Common Pitfalls and How to Avoid Them
-
Copying the entire source tree
Problem: The build context includes test files, documentation, and other assets that inflate the image.
Fix: Use a.dockerignorefile to excludetests/,docs/, and other non‑essential directories. -
Neglecting layer ordering
Problem: Placing a largeCOPY . .early in the Dockerfile invalidates the cache for every subsequent step.
Fix: Group only the files that change frequently together and keep static dependencies at the top. -
Mixing build and runtime in one stage
Problem: The resulting image contains compilers, build tools, and source code.
Fix: Split the build and runtime into separate stages as shown in the example.
The Bottom Line
Docker’s multi‑stage build isn’t just a neat trick; it’s a foundational best practice that delivers tangible savings in storage, network bandwidth, and CI/CD throughput. By carefully structuring your Dockerfile, leveraging caching, and stripping away unnecessary layers, you can reduce image sizes by up to 90 % and cut build times by more than 70 %. The result? Faster deployments, lower operational costs, and a cleaner, more secure container footprint that scales effortlessly across any cloud or on‑prem environment.
Was this article helpful?
Frequently Asked Questions
Stay in the loop
New free tools and practical guides, now and then. No spam, unsubscribe anytime.
Written by
TechVeb Team
The TechVeb team writes practical guides on artificial intelligence, cloud computing, cybersecurity and programming, plus product reviews and free browser-based tools. Edited by Norina Aslam.

Continue Reading
View all →CI/CD Pipeline Best Practices for 2026: Full Guide
Master CI/CD pipeline best practices in 2026. Compare GitHub Actions, GitLab CI, Jenkins, and CircleCI to boost speed, security, and release velocity.

Cloud Cost Optimization: How to Cut Cloud Bills by 60%
Learn proven cloud cost optimization strategies for 2026. Reduce your AWS, Azure, and GCP bills by up to 60% with right-sizing, spot instances, and FinOps.

Cloud Database Comparison: RDS vs Firestore vs Cosmos DB
Compare Amazon RDS, Google Firestore, and Azure Cosmos DB on performance, latency, and cost to choose the best managed cloud database for your application.

Cloud Migration Guide 2026: Strategy & Best Practices
Master cloud migration in 2026 with our step-by-step strategy. Learn assessment, phased roadmaps, tools like AWS and Azure, cost optimization, and security.

Cloud Native Development Guide 2026: Best Practices
Master cloud native development in 2026. Learn 12-factor principles, Kubernetes, containers, and microservices to boost deployment speed and reduce costs.

Cloud Security Best Practices 2026: AWS, Azure & GCP Guide
Master cloud security best practices for 2026. Protect AWS, Azure, and GCP with IAM, encryption, threat monitoring, and compliance strategies.
Comments
Loading comments…