Dockerfile Best Practices: Multi-Stage Builds, Layer Caching and Security

When I joined my first team running containers in production, our Dockerfiles were simple: start from ubuntu:latest, install everything we needed, copy the code, and push. It worked, but our images were 1.2GB, builds took eight minutes, and we had no idea what was actually running inside. A vulnerability scan later revealed we were shipping a full compiler toolchain, git history, and even local environment files into production. That experience taught me that a Dockerfile is not just a build script — it is a definition of your supply chain, your security posture, and your deployment performance. In this article, I'll walk through the patterns I've adopted over years of building and operating container images for Kubernetes workloads, focusing on how to write Dockerfiles that are fast, small, and secure from the start.

Why Most Dockerfiles Waste Time and Disk Space Without Realizing It

In my experience, the most common inefficiency in beginner Dockerfiles is a misunderstanding of how layers work. Every instruction like RUN, COPY, and ADD creates a new immutable layer. Docker stacks these layers to form the final image. If you install dependencies, copy source code, and then clean up in separate layers, the cleanup doesn't actually remove the data — it just hides it in a previous layer that is still part of the image history and still gets pushed to your registry.

Another costly pattern is invalidating the build cache too early. Docker's build cache reuses layers if the instruction and its context haven't changed. I've seen teams copy their entire application code before running npm install or pip install. That means any code change, even a single line comment, invalidates the cached dependency layer and forces a full reinstall. On a Node.js project I worked on, reordering just two lines cut average CI build time from 4 minutes 30 seconds to 47 seconds.

Finally, base image choice matters more than most beginners expect. Starting from a full operating system image like ubuntu:22.04 (around 77MB compressed) or worse, python:3.11 (over 900MB with build tools) when you only need a runtime adds attack surface and slows down every pull. In Kubernetes, where pods are frequently rescheduled and images are pulled across many nodes, that size directly translates to slower scale-up times and higher registry costs. The Docker Documentation recommends starting with the smallest official image that meets your runtime needs, and that advice has held true in every cluster I've operated.

How Layers Affect Image Size and Push/Pull Performance

Think of an image as a stack of transparencies. If one layer adds 500MB of build tools and a later layer runs rm -rf /build-tools, the final filesystem won't show those tools, but the layer containing them still exists. Anyone pulling the image downloads it, and anyone inspecting history can see it. The fix is to combine related operations into a single RUN instruction so temporary files never become a separate layer. For package managers, this also means cleaning the cache in the same step, for example using apt-get clean && rm -rf /var/lib/apt/lists/* immediately after apt-get install.

The Hidden Cost of Using Latest Tags

I've found that using :latest or other mutable tags creates unpredictable builds. One day your build pulls node:latest as Node 18, the next week it's Node 20, and your build breaks in CI with no code change. For reproducible builds, pin to a specific digest or at least a patch version like node:20.11.1-alpine3.19. This also makes security scanning meaningful, because you know exactly which base layer you are scanning and when to update it.

Structuring Multi-Stage Builds to Shrink Production Images by 90%

Multi-stage builds are the single biggest improvement you can make to a Dockerfile. Before they were stable in Docker 17.05, we had to use complex builder patterns with external scripts to avoid shipping build tools to production. Now you can define multiple FROM stages in one Dockerfile and copy only the artifacts you need into the final stage.

The core idea is simple: use a feature-rich builder stage to compile and bundle your application, then copy the result into a minimal runtime stage. Your production image contains only what is needed to run, not what was needed to build. I've used this pattern to reduce a Go service from 820MB to 18MB and a React frontend from 1.1GB to 22MB without changing any application code.

# Stage 1: Build the application
FROM golang:1.22-alpine AS builder
WORKDIR /app
# Copy dependency files first for better caching
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /app/server ./cmd/server

# Stage 2: Minimal production image
FROM alpine:3.19
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
WORKDIR /app
COPY --from=builder /app/server .
# Copy only necessary config, if needed
COPY --chown=appuser:appgroup ./config/prod.yaml ./config/
USER appuser
EXPOSE 8080
ENTRYPOINT ["./server"]

In this example, the builder stage has the full Go toolchain, modules, and source code — easily 400MB+. The final stage is just Alpine plus the static binary. The COPY --from=builder instruction is selective. We don't copy the source, the module cache, or the compiler. The same pattern works for Node, Python, Java, and Rust.

Choosing the Right Runtime Base for Your Language

For compiled languages like Go or Rust, you can often use scratch or distroless as the final stage. For interpreted languages, you need a runtime. I've had good results with python:3.11-slim-bookworm over python:3.11-alpine for Python apps that depend on native extensions, because Alpine's musl libc can cause subtle compatibility issues. For Node.js, node:20-alpine is usually safe. Test your runtime image with your actual workload before committing. A table I use when evaluating options looks like this:

Base Image Strategy Typical Size Use Case Trade-off
scratch 2-10 MB + binary Static Go/Rust binaries No shell, no package manager, hard to debug
distroless (gcr.io/distroless/static) 15-25 MB Go, Java, Node production services Minimal attack surface, no shell, better than scratch for runtimes
alpine:3.19 7-15 MB + runtime General purpose, most languages Very small, needs testing for glibc vs musl
debian:bookworm-slim 60-85 MB + runtime Python, Java with native deps Larger but most compatible, easy debugging

When deploying to Kubernetes, image size directly impacts Horizontal Pod Autoscaler responsiveness. If you're using Kubernetes Autoscaling: HPA, VPA and KEDA for Event-Driven Scaling, smaller images mean new pods become ready faster during a burst, which reduces the need to over-provision.

Keeping Build Context Small with .dockerignore

Multi-stage builds still send your build context to the Docker daemon. If you forget a .dockerignore, you might be sending node_modules, .git, and local secrets every build. In one project, adding a proper .dockerignore reduced context from 450MB to 28MB and build time by 30 seconds before any Dockerfile change. Always include .git, *.log, .env, node_modules (if you run install inside), and any local data directories.

Mastering Layer Caching to Cut Build Times from Minutes to Seconds

Once your Dockerfile is functionally correct, optimizing layer order is where you get time back every day. Docker checks each instruction sequentially. If any file in the build context referenced by a COPY or ADD has changed, that layer and every layer after it must be rebuilt. The trick is to order instructions from least frequently changed to most frequently changed.

For most applications, dependency definitions change less often than source code. So copy and install dependencies first, then copy source code. This way, code changes reuse the cached dependency layer. In my experience, this single reordering is responsible for 70% of CI time savings on Dockerfile builds.

# Inefficient: invalidates npm install on any code change
FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm ci
RUN npm run build
CMD ["node", "dist/index.js"]

# Efficient: leverages layer caching
FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
CMD ["node", "dist/index.js"]

The efficient version only reruns npm ci when package.json or package-lock.json changes. Everything else is cached. I've applied the same logic to Python (requirements.txt before code), Go (go.mod before code), and Java (pom.xml before src).

Using BuildKit Cache Mounts for Package Managers

Traditional layer caching doesn't cache package manager downloads across builds — only the installed result. Docker BuildKit's cache mounts let you persist the download cache itself. This is especially useful for apt, pip, and npm where downloads are large. It requires enabling BuildKit (DOCKER_BUILDKIT=1) which is now default in recent Docker versions. According to the Docker Documentation, BuildKit cache mounts can reduce rebuild time by over 50% for dependency-heavy images without increasing final image size.

# syntax=docker/dockerfile:1.6
FROM python:3.11-slim-bookworm
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]

The --mount=type=cache keeps the pip cache between builds but doesn't include it in the final layer. I've found this cuts our Python CI builds from 2 minutes to about 40 seconds after the first run, with no extra configuration in the runner.

Combining RUN Instructions Without Sacrificing Readability

Combining RUN instructions reduces layers but can become unreadable if overdone. My rule is to combine operations that are logically part of the same setup step and where intermediate files are temporary. Use line continuations and sort packages alphabetically for easier diffs. For example, install system packages, clean up, and create users in one layer, but keep application build steps separate for clearer caching and debugging.

Hardening Your Dockerfile Against Common Supply Chain Attacks

Security in Dockerfiles is not just about scanning at the end — it's about building securely from the first line. I treat every Dockerfile as a supply chain definition. Where your base image comes from, who runs inside the container, and what you ship all matter.

The first step is to run as a non-root user. By default, containers run as root, which means a compromised process has root inside the container. If there's a kernel or container runtime vulnerability, that can escalate. Creating a dedicated user and switching with USER is a low-effort, high-value change. Kubernetes also supports enforcing this with runAsNonRoot in the pod security context, as documented in the Kubernetes Documentation. I always set both: the Dockerfile declares the user, and the deployment enforces it.

Second, minimize what you ship. Use multi-stage builds to avoid shipping secrets, compilers, and package managers to production. Avoid copying .env files, SSH keys, or cloud credentials into the image. If you need secrets at build time (like private npm registries), use BuildKit secret mounts (--mount=type=secret) so they are not persisted in layers.

Third, pin and verify your base images. Instead of FROM alpine:3.19, consider pinning to a digest: FROM alpine:3.19@sha256:.... This guarantees every build uses the exact same bits. Pair this with a tool like Dependabot or Renovate to open PRs when a new digest is available. I've seen teams bitten by a base image update that introduced a breaking change in OpenSSL — pinning avoids that surprise.

Handling Secrets and Build Arguments Safely

ARG and ENV values are visible in image history via docker history and in the final image config. Never pass secrets like API tokens or database passwords as ARG. In my experience, the safest pattern is to inject secrets at runtime via Kubernetes Secrets or external secret managers, and use BuildKit secrets only for build-time access that doesn't persist. If you must use ARG for non-sensitive build configuration, use a default value and override it in CI rather than hardcoding.

Scanning and Updating Without Slowing Down Development

Scanning should be part of your CI pipeline, not an afterthought. Tools like Trivy, Grype, and Docker Scout can scan images for OS and language-level vulnerabilities. I've found that failing the build on high-severity CVEs works well once you have a process to update base images weekly. Automate base image rebuilds on a schedule — even if your code hasn't changed, your base image may have new patches. This is where using a minimal base pays off again: fewer packages mean fewer vulnerabilities to track.

Optimizing Runtime Configuration for Kubernetes Deployments

A Dockerfile that builds a great image can still cause problems in Kubernetes if the runtime configuration is wrong. Two settings I always check are the ENTRYPOINT versus CMD choice and signal handling.

Use the exec form for ENTRYPOINT and CMD (["executable", "param1"]) rather than the shell form (executable param1). The shell form wraps your process in /bin/sh -c, which means your application is not PID 1 and won't receive SIGTERM correctly when Kubernetes tries to terminate the pod. This leads to delayed shutdowns and 30-second termination grace periods being hit every deploy. The exec form ensures signals are forwarded directly. I've debugged many slow rollouts that were fixed by switching to exec form and adding proper signal handling in the app.

Another detail is to set a proper WORKDIR and ensure file ownership matches your non-root user. If you COPY --chown as root and then switch to USER appuser, files will be readable. But if you create files as root after switching back, you can get permission errors at runtime. Define the user early and keep ownership consistent.

Finally, consider how your image will be configured. Avoid baking environment-specific config into the image. Instead, copy a default config and allow overrides via environment variables or mounted ConfigMaps. This keeps one image promotable across dev, staging, and production. If you manage deployments with Helm, this pattern fits well — your Dockerfile provides the binary and defaults, and your Helm Chart Development: Templates, Values, Dependencies and Testing handles environment-specific values and templating without rebuilding the image.

Health Checks and Small Runtime Details

While Kubernetes uses liveness and readiness probes, defining a HEALTHCHECK in the Dockerfile can still be useful for local development and non-Kubernetes environments. Keep it lightweight — a simple curl -f http://localhost:8080/health || exit 1 is enough. Also, set EXPOSE to document the intended port, even though Kubernetes doesn't enforce it. It helps developers and security scanners understand expected network behavior, which is important when you later configure Kubernetes Networking: Services, Ingress Controllers and Network Policies around your workload.

Debugging and Maintaining Dockerfiles at Scale in CI Pipelines

When you have dozens of services, Dockerfile maintenance becomes a team discipline. The best Dockerfiles I've maintained share a few habits that keep them fast and understandable over time.

First, keep Dockerfiles linted. Tools like Hadolint catch common mistakes: missing --no-install-recommends for apt, not pinning versions, using ADD instead of COPY for simple file copies, and running as root. I run Hadolint in CI for every repo that contains a Dockerfile. It takes seconds and prevents many review comments. Pair this with a clear comment explaining non-obvious steps. For example, if you set PYTHONDONTWRITEBYTECODE=1, explain why.

Second, measure what matters. Track image size, build time, and CVE count per service in your CI metrics. In one organization, we added a simple step that echoed image size after each build and posted it to a dashboard. When someone accidentally added a 300MB debug tool to a production image, we saw it the same day. Without measurement, bloat creeps in silently.

Third, standardize base images internally. Instead of each team picking a different base, provide a curated set of approved images: one for Go, one for Node, one for Python, all regularly patched and scanned. This reduces duplication and makes security updates easier. You can extend these with your own Dockerfiles that add common tooling like CA certificates, timezone data, or non-root users, so service teams start from a secure, consistent foundation.

I've found that reviewing Dockerfiles with the same rigor as application code pays off. Ask: does this layer need to exist? Is the cache order optimal? Are we shipping anything we don't need? Those three questions catch most issues before they reach production.

Frequently Asked Questions

Should I use Alpine for every production image?

Not necessarily. Alpine is excellent for size and security, but its musl libc can break Python wheels, Node native addons, or Java dependencies that expect glibc. In my experience, start with Alpine for Go, Rust, and Node, but test Python and Java workloads on both Alpine and Debian slim. If you see build failures or runtime errors related to compiled extensions, Debian slim is often the safer choice with only a modest size increase.

How many stages should a multi-stage Dockerfile have?

Two stages cover most use cases: one builder and one runtime. Add a third stage only if you have distinct needs, like a test stage that runs linters or unit tests, or a separate stage for building frontend assets. More than three stages often indicates you should split into separate images or build pipelines. Keep the final runtime stage as small and focused as possible.

Does layer caching work the same with BuildKit enabled?

BuildKit improves caching but follows the same core principle: order matters. BuildKit adds parallel stage builds and better cache import/export, and its cache mounts provide additional persistence for package managers. For best results, still order instructions from least to most volatile, enable BuildKit in CI, and use --mount=type=cache for large downloads. The Docker Documentation recommends BuildKit for all new projects.

What is the safest way to handle private registry authentication during build?

Use BuildKit secret mounts instead of ARG or COPY. For example, mount an npm token with RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci . The secret is available only during that RUN step and never committed to a layer. At runtime, inject secrets via Kubernetes Secrets or an external manager. Never bake tokens into the image, even in intermediate stages that you think won't be pushed.

Related Articles

References & Standards: Kubernetes Documentation · Docker Documentation · Terraform Documentation