Dockerfile Best Practices Checklist: Build Faster, Smaller, and Safer Container Images
DockerContainersDevOpsBuild OptimizationContainer Security

Dockerfile Best Practices Checklist: Build Faster, Smaller, and Safer Container Images

CCloud Dev Collective
2026-11-09
9 min read

Use this Dockerfile checklist to improve build speed, image size, runtime security, caching, reproducibility, and CI/CD releases.

A Dockerfile affects build speed, image size, runtime security, and release consistency. Use this reusable Dockerfile best practices checklist to review base images, build context, layer order, multi-stage builds, caching, users, secrets, scanning, and tags before shipping a container image.

Overview

A Dockerfile is executable build documentation: it describes how source code and dependencies become a container image. Small choices in that file can create large operational differences. An oversized build context can slow every build, a misplaced dependency step can invalidate the cache, and a development tool left in the final image can expand the attack surface.

The best approach is not to optimize for the smallest possible image at any cost. Optimize for a useful balance of build performance, runtime compatibility, security, debuggability, and repeatability. A production image should contain what the application needs to run and little else. The build process should be understandable, testable, and suitable for local development and CI/CD.

Use the checklist below in three passes:

  • Build design: review the context, base image, dependency installation, layer order, and cache behavior.
  • Runtime design: review the process, user permissions, filesystem behavior, exposed interfaces, and signal handling.
  • Release design: review image tags, provenance, scanning, promotion, and rollback expectations.

These practices complement, rather than replace, cluster controls. If the image will run on Kubernetes, pair this review with a Kubernetes security checklist and validate the resulting deployment with a production deployment checklist.

Checklist by scenario

For every Dockerfile

  • Choose an intentional base image. Select a maintained image that matches the application runtime and operational requirements. Smaller variants can reduce download size, but they may omit shells, package managers, certificates, or debugging tools your application or support process needs.
  • Use a specific base reference. A moving tag can change between builds. Prefer a specific version, and consider recording an image digest when reproducibility and supply-chain control are important. Define a deliberate process for updating that reference rather than relying on accidental changes.
  • Add a .dockerignore file. Exclude version-control metadata, local dependencies, build output, test artifacts, secrets, editor files, and other material that the image build does not need. The Dockerfile and required application files should be easy to identify in the context.
  • Keep one clear responsibility per image. A container can run a web service, worker, or scheduled process. Combining unrelated services makes lifecycle management, scaling, health checks, and troubleshooting harder.
  • Use explicit instructions. Prefer an explicit working directory, startup command, required environment variables, and exposed application port where those declarations help operators understand the image. Document assumptions that are not obvious from the file.

For faster builds and better caching

  • Copy dependency manifests before application source. Install dependencies in a layer that changes only when the manifest or lockfile changes. Copying the entire source tree before dependency installation causes ordinary code edits to invalidate that layer.
  • Order instructions from stable to volatile. Place operating-system packages and dependency installation before frequently changing source files when that order is compatible with the build. Each instruction should invalidate only the work that genuinely depends on it.
  • Use BuildKit-compatible cache mounts where appropriate. Package-manager caches can speed repeated builds without becoming part of the final image. Treat cache mounts as an optimization, not as a substitute for a lockfile or a reliable package source.
  • Make cache use intentional in CI. Decide whether builders share, export, or discard caches. A cache miss should slow a build, not change its result. Avoid relying on undocumented files left by a previous build.
  • Keep the context small. A good .dockerignore improves transfer time and reduces the chance that irrelevant files influence the build. Review it when the repository layout changes.

For smaller production images

  • Use a multi-stage build. Compile or package the application in a builder stage, then copy only the runtime artifact and required assets into a clean runtime stage. This separates compilers and development dependencies from production content.
  • Install only runtime dependencies in the final stage. Development headers, test frameworks, source maps that are not needed operationally, and build tools should not be copied by default. Keep anything retained for diagnostics as a conscious decision.
  • Clean package-manager metadata in the same layer. If an operating-system package manager creates indexes or temporary files, remove them in the same RUN instruction that created them. Removing them in a later layer may not reduce the underlying image history.
  • Do not confuse image size with quality. A smaller image is not automatically safer or easier to operate. Confirm that certificates, timezone data, native libraries, and other runtime requirements remain available.

For a more secure runtime

  • Run as a non-root user. Create or select an application user and switch to it before the runtime command. Verify that the application can read its files and write only to directories that genuinely require write access.
  • Do not copy secrets into the image. Avoid putting tokens, private keys, cloud credentials, or local environment files in the build context. Use the build system's secret-handling features for build-time credentials and the deployment platform's secret mechanism at runtime.
  • Scan the built image. Scan after building, not only the source repository. Review operating-system and application dependencies, understand whether findings affect the runtime path, and define how critical findings are triaged before release.
  • Use a read-only mindset. Design the application to run without modifying its code directory. If temporary files are required, identify the specific writable location and configure it explicitly at deployment time.
  • Keep the final image inspectable. Minimal does not mean opaque. Retain enough metadata, logs, and diagnostic capability for the team to investigate failures without adding broad privileges.

For CI/CD releases

  • Build once and promote the same image. Build and test an immutable image, then promote that image between environments rather than rebuilding different content for each environment.
  • Separate version identity from convenience tags. Human-readable tags can help developers, while immutable identifiers support rollback and auditability. Never make a rollback depend solely on a moving tag.
  • Test the image as a user would run it. Start the container, exercise the main path, verify configuration behavior, and confirm that the process exits or receives termination signals as expected.
  • Automate the checks. Add Dockerfile linting, image scanning, tests, and policy checks to CI. Reusable workflows can help teams standardize these checks; see the GitHub Actions CI/CD pipeline templates guide for related pipeline patterns.

Before deploying to Kubernetes

  • Confirm the image reference points to the intended registry and immutable release.
  • Check that the container listens on the port configured by the workload.
  • Define readiness and liveness behavior outside the Dockerfile when the application needs it.
  • Set resource requests and limits based on observed behavior rather than copying values from an unrelated service.
  • Verify that the non-root user, filesystem permissions, and required capabilities match the pod security settings.
  • Keep configuration and secrets outside the image so the same artifact can move between environments.

If a new image starts and then fails repeatedly, use a structured CrashLoopBackOff troubleshooting decision tree instead of changing several settings at once.

A before-and-after pattern

A fragile pattern often copies the entire repository, installs dependencies, builds the application, and runs everything as the default user in one final image. A stronger pattern separates stable inputs from changing source and uses a runtime stage:

FROM build-image:version AS builder
WORKDIR /src
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM runtime-image:version
WORKDIR /app
COPY --from=builder /src/dist ./dist
COPY --from=builder /src/package.json ./
RUN adduser --disabled-password --gecos '' appuser
USER appuser
CMD ['node', 'dist/server.js']

The exact image names and commands depend on the language and framework. The reusable ideas are the important part: copy manifests first, install from a lockfile, build in a separate stage, copy only the runtime output, and run with reduced privileges. Validate the resulting permissions and startup behavior rather than assuming the pattern fits unchanged.

What to double-check

Before merging a Dockerfile change, inspect the build result rather than reviewing syntax alone.

  1. Dependency reproducibility: Is there a lockfile or equivalent version constraint? Does the build use it consistently? Can a clean builder reproduce the expected artifact?
  2. Base-image updates: Is the chosen runtime still supported by the application? Does the update change certificates, native libraries, user IDs, shell availability, or filesystem paths?
  3. Runtime permissions: Can the configured user read the application and write only where intended? Does the application attempt to create files in a root-owned directory?
  4. Secret exposure: Are credentials absent from the context, Dockerfile arguments, copied files, image history, and generated artifacts? A secret accidentally included during an earlier layer may remain recoverable even if a later instruction deletes the file.
  5. Scanner findings: Which findings are in reachable runtime components, and which are in build-only content? Record the decision and remediation owner rather than ignoring results without explanation.
  6. Failure behavior: Does the main process run in the foreground? Does it receive termination signals? Does the container fail clearly when required configuration is missing?
  7. Image contents: Inspect the final image for compilers, package caches, source code, test data, local configuration, and files that do not belong in production.
  8. Operational ownership: Can the team identify the source commit, build process, dependency inputs, and release tag associated with a running image?

For broader governance, connect image checks to policy as code. OPA or Kyverno-style controls can help enforce organization-specific rules at the right stage, as described in the policy as code guide.

Common mistakes

  • Using latest everywhere: A convenient moving tag makes it difficult to explain what changed and complicates rollback. Use an explicit release process and retain immutable references.
  • Copying the whole repository too early: This makes dependency layers rebuild after every source edit. Copy manifests first and use .dockerignore.
  • Deleting files only at the end: Later deletion does not necessarily remove content from earlier layers. Avoid copying unwanted material in the first place and combine cleanup with installation.
  • Installing development tools in the runtime stage: Multi-stage builds exist to keep build requirements out of the production artifact.
  • Passing secrets through ordinary build arguments: Build arguments can be visible through build metadata or history depending on the tooling. Use an appropriate secret-mount mechanism and keep runtime credentials outside the image.
  • Choosing the smallest base image without testing: Missing certificates, shells, libraries, or debugging utilities can turn a size optimization into a deployment failure.
  • Running as root because permissions are inconvenient: Fix ownership and writable paths deliberately. Do not broaden privileges to hide an unclear filesystem design.
  • Treating a scanner as the entire security program: Scanning is useful feedback, but it does not replace dependency maintenance, least privilege, secure deployment configuration, access review, or incident response. Use the least-privilege access review workflow for the surrounding cloud permissions.

When to revisit

Review a Dockerfile when the workflow or its inputs change, not only when a release is blocked. Revisit it in these situations:

  • Base-image or runtime changes: Check compatibility, permissions, certificates, package behavior, and scanner results after changing the runtime version or image family.
  • Dependency updates: Rebuild from a clean environment, inspect the lockfile, run tests, and rescan the final image.
  • Repository changes: Update .dockerignore and COPY paths when source layout, generated artifacts, or local tooling changes.
  • Build performance degradation: Compare build logs and cache behavior. A new instruction or reordered COPY may be invalidating expensive layers.
  • Deployment changes: Recheck ports, users, writable paths, signals, health behavior, and resource assumptions when moving to a new platform or workload model.
  • Security or incident response: Rebuild affected images from a clean base, rotate any exposed credentials, review image history and registry access, and document the replacement reference. Use an incident response template to keep the response coordinated.
  • Planning cycles: Before a seasonal planning or platform review, sample representative Dockerfiles and compare their build time, size, scan findings, and operational failure patterns. Prioritize repeated problems rather than applying cosmetic rewrites to every image.

For a practical final pass, print or save this checklist with your repository standards. Before the next image release, inspect the context, pin the inputs, verify cache order, build with separate stages, remove secrets, run as non-root, scan the final artifact, test startup and shutdown, and record an immutable image reference. Then repeat the review whenever the application, base image, build workflow, or deployment environment changes.

Related Topics

#Docker#Containers#DevOps#Build Optimization#Container Security
C

Cloud Dev Collective

Cloud DevOps Editorial Team

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.