- Updated: December 13, 2025
- 7 min read
Docker ProTips: Optimize Your Container Builds with Multi‑Stage, Alpine, and Scratch
Docker ProTips: Shrink Images, Speed Up Builds, and Turbo‑Charge Your CI/CD Pipeline

Docker ProTips are a collection of advanced, practical techniques—such as multi‑stage builds, minimal base images, smart .dockerignore usage, and cache‑aware layer ordering—that dramatically reduce image size, cut build times, and make CI/CD pipelines run faster.
Why Docker Optimization Matters Today
DevOps engineers and technical leads constantly battle slow build pipelines, bloated container images, and unpredictable deployment times. In modern micro‑service architectures, a single oversized image can cascade into longer pull times, higher storage costs, and reduced scalability. The original Docker ProTips article highlighted these pain points, and we’re expanding on them with fresh, actionable guidance that aligns with the latest Docker caching and BuildKit capabilities.
Whether you’re a startup racing to ship features or an enterprise looking to tighten security and cost, mastering these ProTips will give you a measurable edge. Below, we break down each tip into bite‑size, MECE‑structured sections that you can quote, implement, and share instantly.
What This Guide Covers
- Multi‑stage builds and the choice between Alpine and
scratchbase images. - Effective
.dockerignorepatterns and optimal layer ordering. - Cache strategies, bind mounts, and CI speed tricks for GitHub Actions, GitLab CI, and Azure Pipelines.
- Real‑world Dockerfile examples you can copy‑paste.
- How UBOS’s low‑code platform can automate these optimizations for you.
Multi‑Stage Builds: The Secret Sauce for Tiny Images
Multi‑stage builds let you separate the heavy‑lifting compile environment from the lean runtime container. The result? A final image that contains only the binary and its runtime dependencies—often under 20 MB.
Alpine vs. scratch: When to Use Which
Both Alpine Linux and the scratch image are popular minimal bases, but they serve different scenarios:
| Aspect | Alpine | scratch |
|---|---|---|
| Size | ≈5 MB (includes musl libc) |
0 B (empty image) |
| Shell Availability | Yes (busybox) | No |
| Use‑Case | When you need debugging tools or a small OS layer. | Pure static binaries (e.g., Go, Rust, C) with CGO_ENABLED=0. |
For Go services compiled with CGO_ENABLED=0, scratch is usually the best choice. For Node.js or Python apps that still need a minimal runtime, Alpine strikes a good balance.
Sample Multi‑Stage Dockerfile (Go + scratch)
FROM golang:1.22-alpine AS builder
WORKDIR /src
ARG CGO_ENABLED=0
COPY . .
RUN go build -ldflags="-s -w" -o /app/main .
FROM scratch
COPY --from=builder /app/main /app/main
ENTRYPOINT ["/app/main"]
This Dockerfile compiles the binary in an Alpine builder, then copies only the executable into a scratch final stage, eliminating all build‑time layers.
Need a visual workflow? Check out the Workflow automation studio on UBOS to model and execute these builds with a drag‑and‑drop interface.
Trim the Context: .dockerignore & Layer Ordering
The Docker daemon sends the entire build context (the directory you run docker build from) to the builder. Unnecessary files—like .git, local caches, or documentation—slow down the transfer and inflate the image cache.
Best‑Practice .dockerignore
# Exclude version control and IDE files
.git
.gitignore
.idea/
.vscode/
# Exclude local build artifacts
node_modules/
dist/
build/
*.log
# Exclude documentation and tests
docs/
test/
*.md
Place this file next to your Dockerfile. Docker will automatically skip the listed paths, reducing context size by up to 90 % in large monorepos.
Layer Ordering for Cache Efficiency
Docker caches each instruction as a separate layer. To maximize cache hits, order layers from least to most frequently changing:
- Base image declaration (rarely changes).
- System package installation (e.g.,
apk add). - Dependency installation (e.g.,
go mod downloadornpm ci). - Copy source code (most volatile).
- Build step (compiles the code).
When you follow this order, a change to a single source file won’t invalidate the expensive dependency‑install layer, shaving minutes off each rebuild.
UBOS’s templates for quick start already embed optimal layer ordering for popular stacks, so you can clone a template and start building instantly.
Cache Strategies & Bind Mounts: Supercharging CI
Modern CI platforms (GitHub Actions, GitLab CI, Azure Pipelines) support Docker’s BuildKit cache mounts, allowing you to persist /root/.cache across builds.
Cache Mount Example (Go)
# syntax=docker/dockerfile:1.4
FROM golang:1.22-alpine AS builder
WORKDIR /src
ARG GOCACHE=/go/.cache
ARG GOMODCACHE=/go/.modcache
RUN --mount=type=cache,target=$GOCACHE \
--mount=type=cache,target=$GOMODCACHE \
go mod download
COPY . .
RUN --mount=type=cache,target=$GOCACHE \
go build -o /app/main .
When the CI runner caches the GOCACHE and GOMODCACHE directories, subsequent builds skip the expensive go mod download step.
Bind Mounts vs. COPY
During development, using --mount=type=bind,source=.,target=/src,readonly can be faster than COPY . . because Docker avoids an extra copy operation. In CI, however, bind mounts are not available, so COPY remains the default.
CI Speed Tricks
- Parallel Stage Builds: Enable
--parallelwith BuildKit to compile independent modules simultaneously. - Layer Caching Across Repositories: Push intermediate images to a private registry and reference them with
--cache-from. - Docker Buildx: Use
docker buildx baketo define reusable build graphs.
UBOS’s Enterprise AI platform by UBOS can orchestrate these BuildKit features across multiple micro‑services, turning a fragmented CI process into a single, observable pipeline.
Ready‑to‑Copy Dockerfile Samples
Node.js App with Alpine + Cache
# syntax=docker/dockerfile:1.4
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci --omit=dev
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:20-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
EXPOSE 3000
CMD ["node","dist/index.js"]
Python Flask Service Using scratch (via pyinstaller)
# Builder
FROM python:3.12-slim AS builder
WORKDIR /src
RUN pip install --no-cache-dir pyinstaller
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
RUN pyinstaller --onefile app.py
# Runtime
FROM scratch
COPY --from=builder /src/dist/app /app
ENTRYPOINT ["/app"]
These examples illustrate the same principles: isolate heavy tooling, cache dependencies, and ship only the runtime artifact.
Looking for a pre‑built template? The AI Article Copywriter template demonstrates a full CI/CD pipeline with Docker multi‑stage builds already baked in.
Key Benefits & Immediate Takeaways
- Image Size Reduction: From 300 MB to < 20 MB on average, cutting network transfer time by up to 90 %.
- Faster Builds: Proper caching can shave 2–5 minutes per CI run for typical Go/Node projects.
- Security Hardening: Minimal base images contain fewer attack surfaces.
- Cost Savings: Smaller images reduce storage fees on container registries and cloud providers.
- Developer Happiness: Faster feedback loops mean less waiting and more shipping.
To embed these practices into your organization, follow this quick checklist:
- Audit existing Dockerfiles for unnecessary layers.
- Add a comprehensive
.dockerignorefile. - Refactor to multi‑stage builds using Alpine or
scratch. - Enable BuildKit and configure cache mounts in your CI.
- Leverage UBOS’s low‑code automation to generate and maintain Dockerfiles.
Take the Next Step with UBOS
Ready to automate Docker optimization across all your services? UBOS offers a suite of tools that make the process painless:
- UBOS solutions for SMBs – pre‑configured pipelines for small teams.
- UBOS for startups – fast‑track your MVP with ready‑made Docker templates.
- UBOS partner program – collaborate and co‑sell optimized container solutions.
- UBOS pricing plans – transparent, usage‑based pricing that scales with your CI load.
- UBOS portfolio examples – see real‑world case studies of Docker‑first deployments.
Explore the About UBOS page to learn how our AI‑driven platform can continuously apply these ProTips, keeping your containers lean and your pipelines swift.
Andrii Bidochko
CTO UBOS
Andrii Bidochko is an AI entrepreneur and researcher focused on AI agents, reinforcement learning, and autonomous systems. He writes about the technologies shaping the future of machine intelligence, from frontier models and agent architectures to real-world AI applications.