Docker best practices
The handful of habits that turn a bloated, insecure image into a small, fast, safe one.
Good Docker images start from a small official base like alpine or distroless, use multi-stage builds to leave build tools behind, and order their layers so unchanged steps are reused from cache. A .dockerignore keeps the build context lean, versions are pinned for reproducibility, containers run one process as a non-root user, and images are scanned for vulnerabilities before shipping.
Start from a small official base
The base image is the foundation everything else sits on, so choose one that is small and trusted. Official minimal images like alpine (a few megabytes) or distroless (no shell or package manager at all) shrink both the download size and the attack surface. A slim base means faster pulls, less to patch, and fewer CVEs riding along for free.
Multi-stage builds
A multi-stage build uses one stage with full compilers and dev dependencies to produce the artifact, then copies only that artifact into a clean, tiny final stage. The heavy build toolchain never ships to production, so a 1 GB build environment can yield a 20 MB runtime image. This is the single biggest lever for both size and security in most images.
Order layers for cache reuse
Each Dockerfile instruction is a cached layer, and Docker reuses cache up to the first line that changed. So put rarely-changing steps first — copy your dependency manifest and install dependencies before copying your fast-changing source code. Done right, a code edit rebuilds in seconds instead of reinstalling every dependency; a .dockerignore keeps unrelated file churn from busting that cache.
Minimize and pin
Fewer, deliberate layers keep images lean, so chain related commands and clean up package caches within the same RUN. Pin versions explicitly — a base tag, package versions, dependency locks — so a rebuild months later produces the same image instead of silently pulling something newer. Reproducibility is what makes an image you can trust and roll back to.
Non-root, one process
By default containers run as root, so create and switch to an unprivileged user to limit the blast radius if the process is compromised. Run a single main process per container, which keeps the unit of scaling, logging and restarting clean and lets the orchestrator manage lifecycle. If you need several processes, run several containers.
Scan before you ship
Even a careful image inherits vulnerabilities from its base and dependencies over time, so scan it with a tool like Trivy or Docker Scout in the pipeline. Scanning catches known CVEs before the image reaches production and flags when a base needs rebuilding. Combined with a small base, it keeps the ongoing patching burden manageable.
Why image hygiene matters
A Docker image is the unit you build once and run everywhere, so its qualities are multiplied across every environment, every deploy and every running container. A bloated, careless image is not just an aesthetic problem — it's slower to build, slower to push and pull, slower to start, more expensive to store, and larger as an attack surface. A naive Dockerfile that starts FROM ubuntu, installs a compiler, copies the whole repository and runs as root can easily be over a gigabyte, ship dozens of known vulnerabilities, and rebuild from scratch on every code change.
The good news is that a small set of well-understood practices fixes almost all of it. None of them are exotic; they're habits. Applied together they routinely turn a 1 GB image into a 20 MB one, cut build times from minutes to seconds, and dramatically shrink the security footprint. The themes running through all of them are the same: keep it small, keep it reproducible, keep it least-privileged.
Small bases and multi-stage builds
Everything starts with the base image, because it's the floor your image is built on and you inherit all of its size and all of its vulnerabilities. Prefer small, official images. alpine is a popular minimal Linux at a few megabytes; distroless images go further, containing only your app and its runtime with no shell or package manager at all — which is both tiny and hard to attack, since there's no bash for an intruder to use. Official images are maintained and patched, unlike random images off the internet.
The most powerful size tool is the multi-stage build. Many apps need a heavy toolchain to build — compilers, dev headers, package managers — but none of that is needed to *run* the result. A multi-stage Dockerfile uses a first stage with the full toolchain to produce the artifact, then a second, clean stage that copies in only the finished binary or bundle:
- Stage one:
FROM golang AS build… compile the binary. - Stage two:
FROM distroless…COPY --from=build /app /app.
The final image contains the app and nothing else. The gigabyte of build tooling is discarded. This single technique often does more for size and security than everything else combined.
The layer cache and build context
Docker builds images as a stack of layers, one per instruction, and it caches them. On a rebuild it reuses cached layers up to the first instruction whose inputs changed, then rebuilds everything after. Understanding this turns slow builds into fast ones.
The rule is: order instructions from least- to most-frequently-changing. Your dependencies change rarely; your source code changes constantly. So copy the dependency manifest and install dependencies *first*, and copy the application source *after*:
- Copy
package.json/requirements.txt/go.mod. - Install dependencies (this expensive layer is now cached).
- Copy the rest of the source.
Now editing a source file only invalidates the cheap final layers; the expensive dependency install is reused. Get the order backwards and every one-character change reinstalls everything.
Complementing the cache is the `.dockerignore` file, which excludes files from the build context sent to the daemon. Ignoring .git, node_modules, local env files and build output keeps the context small (faster builds), prevents secrets from accidentally landing in an image, and stops irrelevant file churn from busting the cache. Also minimize layers by chaining related commands — combine an apt-get update && install && rm -rf /var/lib/apt/lists/* into one RUN so the cleanup happens in the same layer rather than leaving the cache bloating an earlier one.
Reproducibility and runtime security
An image you can't rebuild identically is a liability, so pin your versions. Avoid the latest tag, which is a moving target; pin the base image to a specific tag or digest, pin package versions where you can, and commit a lockfile so dependency resolution is deterministic. Then a rebuild six months from now produces the same image rather than silently pulling a newer, subtly different set of packages — and a known-good image is one you can confidently roll back to.
Two runtime practices matter most. First, run as a non-root user. Containers default to root, and a process running as root inside a container that escapes its isolation is root on concerns you care about. Create an unprivileged user in the Dockerfile and USER into it, so a compromised process has minimal privileges. Distroless and other minimal bases reinforce this by removing the tools an attacker would reach for.
Second, one process per container. A container should have a single main concern — one web server, one worker — so that scaling, logging, health-checking and restarting all map cleanly to it, and the orchestrator can manage its lifecycle. Cramming a database, a web server and a cron daemon into one container defeats the model; if you need several processes, run several containers and let the orchestrator coordinate them.
Scanning and putting it together
Even a perfectly built image rots over time, because vulnerabilities are discovered in bases and dependencies long after you shipped. So scan images for known CVEs with a tool like Trivy, Grype or Docker Scout, ideally as a step in your CI/CD pipeline that can fail the build on critical findings. Scanning both catches problems before they reach production and tells you when a base image needs rebuilding on a fresh, patched foundation — which is cheap precisely because you kept the image small.
Put the habits together and a healthy pipeline looks like this: a Dockerfile that starts from a pinned, minimal official base; a multi-stage build that leaves the toolchain behind; instructions ordered so dependency layers cache and only code layers rebuild; a .dockerignore guarding the context; a non-root USER and a single main process; and a scan gate before the image is pushed to the registry and deployed.
The mindset behind all of it is that an image is a build artifact you'll produce thousands of times and run everywhere, so every kilobyte, every extra layer, every needless privilege and every unpatched package is a cost paid repeatedly. Small, reproducible, least-privileged images aren't perfectionism — they're what make containers fast to ship, cheap to run and safe to trust.
Start from a small, official base image — alpine or distroless — to shrink size and attack surface.
Use multi-stage builds so compilers and build dependencies never reach the final image.
Order layers from least- to most-frequently-changing so Docker reuses the build cache.
A .dockerignore keeps secrets and junk out of the build context and speeds up builds.
Run as a non-root user and one process per container for security and clean lifecycle management.
Pin versions, minimize layers, and scan images for known vulnerabilities before deploying.
Quick quiz
What is the main benefit of a multi-stage build?
Why copy the dependency manifest and install dependencies before copying source code?
How Docker works
Package an app and everything it needs into one portable, isolated unit.
How Kubernetes works
You declare the desired state; the cluster relentlessly makes it real.
CI/CD pipeline explained
Turn every commit into a tested, shippable, deployable artifact — automatically.
Infrastructure as code
Describe your servers, networks and databases in files you can review, version and replay.