Dockerfile Best Practices: Smaller, Faster, Safer Images

Dockerfile Best Practices: Smaller, Faster, More Secure Images

Introduction

A Dockerfile is a short text file with an outsized effect. It decides how big your image is, how long your builds take, how many known vulnerabilities ship inside it, and whether a container that escapes its process boundary runs as root on the host. A careless Dockerfile can turn a small application into a huge image that takes minutes to pull on every deploy, carries a compiler and a package manager it never needs at runtime, and runs as root by default. A good one does the opposite: it builds fast because the cache works for it, it ships only what the application needs, and it gives an attacker almost nothing to work with.

This guide covers Dockerfile best practices as they stand on 30 November 2026, against Docker Engine 29.10.1, released 24 November 2026, with BuildKit 0.35.1 as the builder. Every practice below is one Docker itself documents or that follows directly from how layers and the build cache work. There is a worked example at the end — a Python web service taken from a naive first draft to a production-ready multi-stage Dockerfile — so you can see each rule change the result rather than just reading about it. If you are new to Docker itself, start with our Docker Tutorial for Beginners; if you already run containers and want to orchestrate them, our Docker Compose Tutorial is the next step.

The short version: pin your base image, order instructions so the cache works, keep the build context small with a .dockerignore file, use multi-stage builds, run as a non-root user, and scan the finished image. The rest of this guide is the evidence for those six sentences.

How Docker Builds an Image — Layers and the Cache

A Dockerfile is a list of instructions, and each instruction creates a layer. A layer is a read-only snapshot of the filesystem changes that instruction made: the files it added, the files it changed, the files it deleted. The finished image is the stack of those layers, and a container is the same stack plus a thin writable layer on top. That stacking is what makes Docker fast and what makes it wasteful, depending on how you write the file.

The build cache is the key idea. When you rebuild an image, BuildKit reuses a cached layer if the instruction and its inputs have not changed. The moment one instruction changes, that layer is rebuilt — and so is every layer after it, because each layer is built on top of the one before. This single rule explains most Dockerfile advice. If you copy your source code into the image before installing dependencies, then every code change invalidates the dependency-install layer and reinstalls everything. If you copy the dependency list first, install, and only then copy the source, a code change rebuilds just the last layers. The order of instructions is therefore a performance decision, not a style choice.

Layers are also additive. If a layer downloads a 300 MB compiler and a later layer deletes it, the image is not 300 MB smaller — the deletion is recorded as a new layer, but the earlier layer still exists in the image and still has to be downloaded. That is why the advice is always to install and clean up in the same RUN instruction, and why multi-stage builds matter: the only way to truly leave something out of an image is for it never to be in the final stage at all.

The build context matters too. When you run docker build, the client sends the build context — the directory you point it at — to the daemon. If that directory contains a .git folder, a local virtual environment, log files and a .env file with secrets, all of it is sent on every build, and COPY . . will copy it into the image. A .dockerignore file is the fix: list what should never reach the daemon. A secret that reaches the build context can end up baked into a layer, where anyone with the image can read it.

One more piece of context for 2026: BuildKit has been the default builder since Docker 23.0, and Engine 29.10 ships BuildKit 0.35.1, which provides the cache mounts, secret mounts and parallel stage execution this guide relies on. The # syntax=docker/dockerfile:1 directive at the top of the example Dockerfiles asks BuildKit for the current stable Dockerfile frontend.

Choose and Pin a Base Image

The first line of a Dockerfile is the most consequential decision in the file, because everything else is built on top of it. The base image sets the operating system, the language runtime, the size of the image, and the number of known vulnerabilities it contains before you have written a single line of your own.

Start with an official image. Docker Official Images are a curated set maintained with the upstream projects, with clear documentation and regular updates. For language runtimes, the official image usually comes in several variants, and the variant matters as much as the name. A Python image, for example, is available as the full image, a slim variant based on Debian with most packages stripped out, and an alpine variant based on Alpine Linux with musl libc instead of glibc. The full image is the easiest to build against and the largest; slim is the usual sweet spot for production; Alpine is the smallest, but its different C library has historically broken compiled extensions, so test it before committing to it. Docker's own guidance is to choose a minimal base image that matches your requirements, and to use two types of base image where it helps: one for building and testing, and a slimmer one for production — which is exactly what multi-stage builds do.

Pin the version, and pin it precisely. FROM python:latest means a different image every time the tag moves, so a rebuild next month can silently change your runtime and libraries — and you will not know which build introduced the change. FROM python:3.13-slim pins the minor version and the variant, and naming the Debian release, as in python:3.13-slim-trixie, pins the distribution too. The strongest form is a digest, FROM python:3.13-slim@sha256:..., which pins the exact image bytes — the right choice where reproducibility matters. Whichever form you choose, rebuild regularly: a pinned image that is six months old carries six months of unpatched vulnerabilities. Use docker build --pull to force a fresh check for a newer base image even when a cached one exists.

Distroless images deserve a mention: Google's distroless images contain only the application and its runtime dependencies — no shell, no package manager, no extra tools. They are the smallest and most defensible runtime images available, and an excellent choice for compiled languages like Go and Java. The trade-off is debuggability: with no shell to exec into, you need the kubectl debug ephemeral-container workflow or good logging instead.

Order Instructions for the Cache and Keep Layers Few

If the base image is the first decision, instruction order is the second, and it saves the most build time. The rule is simple: copy files in order of how rarely they change. The dependency list changes occasionally; the source code changes constantly. So copy the dependency list, install, and only then copy the source:

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

With that order, a code change rebuilds only the final COPY layer and whatever follows it. With the reverse order — COPY . . first, then the install — every code change reinstalls every dependency. On a project with a large dependency tree, that is the difference between a five-second rebuild and a five-minute one, multiplied by every developer and every CI run.

Combine related commands into a single RUN instruction, and clean up in the same instruction. This is the layer-additivity rule from the first section: a package cache deleted in a later layer still occupies space in the image. The correct pattern installs, then removes the cache, in one layer:

RUN apt-get update && apt-get install -y --no-install-recommends \
        build-essential \
    && rm -rf /var/lib/apt/lists/*

The --no-install-recommends flag matters on Debian-based images: it skips the recommended packages that are not required, which can halve the size of an install. The rm -rf /var/lib/apt/lists/* at the end removes the package lists in the same layer, so they never reach the image. Note that apt-get update and apt-get install must be in the same RUN — if they are split across layers, the update layer can be cached while the package index it fetched goes stale, and the install then fails or installs the wrong versions.

Prefer COPY over ADD. ADD has two extra behaviours — it extracts tar archives and fetches remote URLs — and both are surprises waiting to happen. COPY does one thing: it copies files from the context into the image. If you need to download something, do it explicitly with curl inside a RUN, where the command is visible and its failure is obvious. Similarly, prefer the exec form of CMD and ENTRYPOINT — CMD ["python", "app.py"] — over the shell form, CMD python app.py. The exec form runs the process directly, so it receives signals correctly; the shell form wraps it in a shell, which can swallow the signal that tells a container to stop gracefully, and is a common cause of containers that take ten seconds to die on shutdown.

Use WORKDIR instead of cd in RUN commands. WORKDIR /app sets the working directory for every instruction that follows, it creates the directory if it does not exist, and it is readable at a glance. A RUN cd /app && ... hides the same fact inside a shell command that only applies to that one layer.

Multi-Stage Builds — Leave the Build Tools Behind

Multi-stage builds are the single most effective Dockerfile technique, and they are the reason the naive-versus-optimised image sizes in this guide differ by an order of magnitude. A multi-stage Dockerfile uses several FROM instructions: one stage builds the application, and a second, clean stage runs it. Only what you explicitly copy from the build stage into the final stage ends up in the image, so compilers, headers, test frameworks and package caches stay behind.

Here is the shape of it for a compiled language, in this case Go:

# syntax=docker/dockerfile:1
FROM golang:1.25 AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /app/server ./cmd/server

FROM scratch
COPY --from=builder /app/server /server
USER 10001
EXPOSE 8080
ENTRYPOINT ["/server"]

The builder stage is a full Go toolchain image. It downloads the modules, compiles the binary, and is then discarded. The final stage is scratch — an empty image — containing only the compiled binary. Nothing else exists in the image: no shell, no package manager, no compiler, no source code.

The same pattern works for interpreted languages. A Python application can install its dependencies into a virtual environment in a build stage, then copy only the virtual environment and the application code into a slim runtime stage. A Node.js application can run npm ci and npm run build in a build stage, then copy only the built output and the production dependencies into the runtime stage. The principle is identical in every language: the build stage may be large and messy, because it never ships; the runtime stage is kept small and clean, because it does.

Name your stages with AS: COPY --from=builder reads better than COPY --from=0, and survives reordering — a numeric reference silently points at the wrong stage if you insert one later. You can also build a single stage on demand with docker build --target builder, which is useful for running tests in the build environment without producing a runtime image.

Run as Non-Root and Keep Secrets Out of the Image

By default, a container runs as root. That is the single most dangerous Dockerfile default, because a process that escapes its container — or a vulnerability in the application itself — then has root privileges on the host. The fix is one instruction, placed near the end of the Dockerfile, after everything that needs root has finished:

RUN groupadd -r app && useradd -r -g app app
USER app

Create a dedicated user and group, then switch to them. The USER instruction applies to everything after it, including the CMD, so the application itself runs unprivileged. Two details matter. First, use a fixed numeric UID and GID — USER 10001 is unambiguous, and Kubernetes securityContext settings like runAsNonRoot check the numeric UID, not the name. Second, make sure the application can still do what it needs: any directory it writes to must be owned by the application user, which is why the worked example below uses COPY --chown=app:app.

Secrets must never be baked into an image. Do not put an API key, a password or a private key in an ENV instruction, in a COPY of a .env file, or in a RUN command that downloads something with credentials — every one of those ends up in a layer, and layers are readable by anyone who can pull the image. The correct mechanisms are BuildKit's secret mount and the runtime's own secret handling. A BuildKit secret mount passes a secret into a single RUN instruction without storing it in any layer:

RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
    npm ci

The secret is available during that command and gone afterwards. At runtime, pass secrets as environment variables from your orchestrator or secrets manager, or mount them as files — never bake them into the image, and never commit them to the repository the Dockerfile lives in. The .dockerignore file is the backstop here: it should exclude .env, any *.pem or *.key files, and credential files, so that even a careless COPY . . cannot pick them up. Our Git for DevOps Engineers guide covers keeping secrets out of repositories, and the same discipline applies to images.

Health Checks, Signals and the Worked Example

A production image should tell its orchestrator whether it is healthy, and it should stop cleanly when asked. Both are small additions with large operational effects.

A HEALTHCHECK runs a command inside the container on a schedule, and Docker reports the result as the container's health status. Kubernetes has its own probes and does not use the Docker health check, but for Docker Compose, Docker Swarm and local development it is the mechanism that tells you a container is up but not actually working:

HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

The --start-period matters: it gives the application time to start before failures count, so a slow-starting application is not marked unhealthy during its normal startup. Keep the health check cheap — a single HTTP request to a lightweight endpoint, not a database query — because it runs every thirty seconds for the life of the container.

Signals are the other half. When Docker stops a container it sends SIGTERM, waits ten seconds, then sends SIGKILL. An application that handles SIGTERM shuts down cleanly — finishing in-flight requests, closing connections, flushing buffers. One that does not is killed mid-request after the grace period. The exec form of CMD matters here: it makes the application PID 1, so it receives the signal directly, while a shell-form CMD leaves a shell as PID 1 that may not forward it. If your application cannot handle SIGTERM, a tiny init process such as tini can be the entrypoint and will forward signals and reap zombie processes.

Now the worked example. The project is a small Python web service: an app.py, a requirements.txt with two dependencies, and a test suite. This is the Dockerfile most people start with:

FROM python:latest
COPY . .
RUN pip install -r requirements.txt
CMD python app.py

It has every problem in this guide: an unpinned latest tag, the whole context copied before the install (so the .git folder, the virtual environment and any .env file are all in the image, and every code change reinstalls the dependencies), no .dockerignore, no non-root user, no health check, and the shell form of CMD. And here is the production version of the same service:

# syntax=docker/dockerfile:1
FROM python:3.13-slim AS build
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install --no-cache-dir -r requirements.txt

FROM python:3.13-slim AS runtime
RUN groupadd -r app && useradd -r -g app -m app
WORKDIR /app
COPY --from=build /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY --chown=app:app app.py ./
USER app
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
CMD ["python", "app.py"]

With a .dockerignore that excludes .git, __pycache__, .venv, *.pyc, .env and the test files, this version is a fraction of the size of the first, rebuilds in seconds when only the code changes, runs as a non-root user, and reports its own health. The --mount=type=cache on the pip install is a BuildKit cache mount: the pip download cache survives between builds without being copied into the image, so a rebuild with one new dependency downloads only that dependency. That is the whole guide in one file, and it is a good template to copy for your own services.

Checklist, Scanning and Keeping Images Fresh

Before an image reaches production, run through this checklist. It takes five minutes and catches the mistakes that cost hours later.

Check What to verify How
Base image pinned Specific version, not latest Read the FROM line; prefer a digest in production
Build context small .dockerignore excludes .git, .env, virtual environments, logs docker build shows the context size; it should be kilobytes, not hundreds of megabytes
Cache order correct Dependency list copied and installed before source code Change one source file and rebuild; only the last layers should rebuild
Multi-stage Build tools absent from the final stage docker history on the final image shows no compiler or package manager layers
Non-root user USER is set and the app owns its writable directories docker run --rm myapp id prints a non-root UID
No secrets in layers No ENV with credentials, no copied .env docker history --no-trunc shows no secret values
Health check present HEALTHCHECK hits a cheap endpoint with a start period docker inspect shows the health check configuration
Image scanned Known vulnerabilities reviewed before deploy docker scout cves myapp or Trivy in CI
Size reasonable Final image close to the runtime plus the app docker images — compare against the naive version

Scanning deserves a paragraph of its own. An image built from a pinned base can still contain vulnerabilities — in the base image's system packages, in your language dependencies, or in a library you installed along the way. Docker Scout is built into Docker and reports vulnerabilities with fix guidance; Trivy is a widely used open-source scanner that is easy to add to a CI pipeline. Scan on every build and fail the build on critical vulnerabilities with a known fix, rather than scanning occasionally and discovering the problem in production. A scan result is a starting point, not a verdict: a vulnerability in a package your application never loads is less urgent than one in the web framework that handles every request.

Finally, images rot. A pinned base image does not update itself, and neither does a dependency list. Rebuild on a schedule — weekly is a good default for production services — with docker build --pull so the base image is refreshed, and use a dependency-update tool to open pull requests when libraries change. An image that is rebuilt regularly, scanned on every build and kept small is an image you can deploy with confidence.

FAQ

What is the current Docker Engine version?

Docker Engine 29.10.1, released 24 November 2026, is the current version as of 30 November 2026, with BuildKit 0.35.1. Engine 29.10.0 arrived on 16 November 2026. Re-check the release notes at publication time, as Docker ships patches frequently.

Should I use Alpine, slim or distroless as a base image?

Use slim for most production services: it is small, it uses the standard glibc, and it rarely breaks compiled extensions. Use Alpine when size matters most and you have tested it with your dependencies. Use distroless for compiled languages where you want the smallest possible attack surface and can debug without a shell.

Why is my Docker build slow even though I changed one file?

Because an early layer changed and every layer after it rebuilt. The usual cause is copying the source code before installing dependencies. Copy the dependency list, install, and only then copy the source — then a one-file change rebuilds only the last layers.

Is running as root in a container really a problem?

Yes. A container process that escapes, or an application vulnerability, has root privileges on the host if the container runs as root. Create a dedicated user and switch to it with USER near the end of the Dockerfile, and make sure the application owns the directories it writes to.

How do I keep secrets out of my Docker image?

Never put credentials in ENV, in a copied .env file, or in a RUN command. Use a BuildKit secret mount for secrets needed at build time, pass secrets as environment variables or mounted files at runtime, and exclude credential files in .dockerignore so a careless COPY . . cannot pick them up.

Conclusion

A good Dockerfile is a short file that does six things well: it pins a minimal base image, it orders instructions so the cache works, it keeps the build context small, it uses multi-stage builds to leave build tools behind, it runs as a non-root user, and it keeps secrets out of the image. Against Docker Engine 29.10.1, the tools for all six are built in — BuildKit cache and secret mounts, the # syntax=docker/dockerfile:1 frontend, and docker scout for scanning — so there is no reason to ship the naive version any longer.

Start with the worked example in this guide and adapt it to your own service: change the language, keep the structure, and run the checklist before the image reaches production. Then go deeper with our Docker Tutorial for Beginners if any of the concepts need a fuller introduction, and our Docker Compose Tutorial when you are ready to run the image alongside a database and a reverse proxy.

Sources checked 30 Nov 2026: Docker Docs, Engine version 29 release notes (29.10.1, 24 Nov 2026; 29.10.0, 16 Nov 2026; BuildKit 0.35.1; Go 1.27.4; API 1.57; experimental daemon jobs; loopback insecure-registry behaviour change in 29.10.0); Docker Docs, Building best practices (multi-stage builds, minimal base images, .dockerignore, rebuilding regularly, --pull and --no-cache flags, ephemeral containers). NOT VERIFIED and therefore not stated as fact above: any specific before/after image size for the worked example (sizes vary by project — measure your own with docker images); the claim that any particular scanner finds a specific number of vulnerabilities. External references: Docker Docs — Building best practices · Docker Docs — Docker Engine version 29 release notes.

—

Scroll to Top