A well-structured Dockerfile can make builds faster, images smaller, and production deployments easier to review. This reusable checklist covers Dockerfile best practices for layer ordering, build caching, multi-stage builds, runtime security, secrets, health checks, and image provenance.
Overview
A Dockerfile is both a build recipe and part of your application’s operational documentation. Small changes in instruction order, dependency handling, or the selected base image can affect build time, image size, vulnerability exposure, and the behavior of the container at runtime.
The right goal is not simply the smallest possible image. A production image should contain the files and runtime dependencies the application needs, while excluding source artifacts, package managers, credentials, caches, and build tools that are unnecessary after compilation. It should also run with a clear command, a suitable user, and a predictable configuration model.
Use the following checklist during a new service setup, dependency update, failed-build investigation, or production hardening review. Test the result in the same kind of CI and runtime environment used by the application; an image that builds locally may still have problems with architecture, permissions, networking, or startup behavior elsewhere.
Dockerfile instruction reference
- FROM: Selects the base image. Prefer a maintained, purpose-appropriate runtime image and make the version or digest policy explicit.
- WORKDIR: Sets the working directory for later instructions and the container process. Use it instead of scattering directory changes through shell commands.
- COPY: Adds files from the build context. Copy only what is needed, and use a
.dockerignorefile to reduce the context. - RUN: Installs packages or performs build operations. Combine related package-manager operations and clean temporary data in the same layer where appropriate.
- ENV: Sets environment variables that become part of the image configuration. Do not use it for secrets.
- ARG: Defines build-time variables. Treat values passed through build arguments as potentially visible in build metadata or history.
- USER: Selects the user for subsequent instructions and the default process. Use a non-root runtime user where the application supports it.
- ENTRYPOINT and CMD: Define the default executable and its arguments. Prefer exec-form JSON syntax for reliable signal handling.
- HEALTHCHECK: Describes how to assess container health when the runtime uses this instruction. It should test meaningful application readiness, not merely that a process exists.
Checklist by scenario
For faster builds and reliable cache use
- Create a focused
.dockerignore. Exclude version-control metadata, local dependency directories, test output, editor files, logs, secrets, and other files that are not needed by the build. - Order instructions from stable to frequently changing. Copy dependency manifests before application source, install dependencies, and copy the source afterward.
- Use the package manager’s lockfile when the project supports one. This makes dependency resolution more repeatable and allows cache reuse without silently changing the dependency graph.
- Keep unrelated build steps separate when that makes cache behavior easier to understand. Combine package installation and cleanup when temporary package indexes or archives would otherwise remain in a layer.
- Use BuildKit features deliberately, such as cache mounts for package managers where they are supported by the team’s builder. Document any builder requirement in the project’s build instructions.
- Build with a clean context in CI at least once during review. A local cache can hide missing files, accidental dependencies, or an incorrectly configured ignore file.
For smaller production images
- Use a multi-stage Docker build. Compile or bundle the application in a builder stage, then copy only the runtime artifacts into a separate final stage.
- Choose the final image based on runtime requirements, not habit. A minimal image is useful only when the application and its operational tooling work correctly with it.
- Remove compilers, headers, package managers, source code, test fixtures, and development dependencies from the final stage whenever they are not required at runtime.
- Check whether native modules, certificates, time-zone data, shells, or debugging utilities are needed. Removing required runtime data can make an image smaller but unusable.
- Inspect the resulting image contents and compare image size by layer. Optimization should be guided by what is actually present rather than by the number of Dockerfile lines.
For safer runtime containers
- Run as a dedicated non-root user when possible. Ensure the application directory, temporary paths, and mounted locations have the permissions the process needs.
- Do not copy
.envfiles, private keys, cloud credentials, package-manager tokens, or other secrets into the build context or image. - For sensitive build-time inputs, use the secret-handling capabilities of the selected builder instead of
ARGorENV. Verify that the secret is not written into a generated file or retained in a layer. - Pin base-image and dependency choices according to the project’s review policy. Tags communicate intent, while digests can make a particular image artifact reproducible; teams should decide how updates are introduced and reviewed.
- Scan the final image and, where useful, the source and dependency manifests. Review whether a reported issue is reachable and relevant, but do not ignore findings without recording the decision.
- Generate and retain build metadata such as an SBOM or provenance information when the build platform supports it and the team’s release process uses it. Metadata improves traceability; it does not replace secure configuration or vulnerability review.
For predictable startup and operations
- Use an explicit
WORKDIR, a clear default command, and environment variables for deployment-specific configuration. - Prefer
ENTRYPOINT ["executable", "arg"]andCMD ["default-arg"]over shell-form commands when the process must receive termination signals correctly. - Make the application log to the container’s standard output and error streams unless the platform explicitly requires another arrangement.
- Add a health check only when it represents a useful operational test. A check should have a reasonable timeout, interval, and failure behavior for the service.
- Test graceful shutdown, read-only filesystem assumptions, temporary-file use, and behavior when optional environment variables are absent.
Multi-stage build comparison
| Approach | What ships | Typical trade-off |
|---|---|---|
| Single-stage build | Build tools, source, dependencies, and runtime files may all remain together | Simple to start, but often larger and harder to audit |
| Multi-stage build | Only selected artifacts are copied into the final runtime stage | Requires clear knowledge of runtime dependencies and permissions |
| Minimal runtime image | A narrowly selected runtime and application files | Can reduce contents, but may require extra work for certificates, debugging, or native libraries |
A common pattern looks like this:
FROM build-image AS builder
WORKDIR /src
COPY package.json package-lock.json ./
RUN install-command
COPY . .
RUN build-command
FROM runtime-image
WORKDIR /app
COPY --from=builder /src/dist ./dist
USER app
ENTRYPOINT ["runtime", "dist/server.js"]
Replace the placeholder image names and commands with those appropriate for the application. The important pattern is the boundary: development and compilation happen in one stage, while the final stage receives only the required runtime output.
What to double-check
Build context and file ownership
Read the Dockerfile together with .dockerignore. Confirm that every file referenced by COPY is intentionally available, and that no ignored file is required only because a local workstation happens to have it. Then check ownership after copying files into a non-root image. A build can succeed while the application later fails because it cannot read its configuration or write to a temporary directory.
Architecture and native dependencies
If images are built on one architecture and run on another, native binaries and compiled modules deserve specific testing. Confirm the builder, base images, and release pipeline support the architectures your deployment targets. Do not assume that a successful local build proves cross-platform compatibility.
Cache correctness
Cache reuse should speed up a correct build, not conceal changed inputs. Verify that dependency files are copied before installation and that source changes invalidate the steps that need to run again. When troubleshooting, perform a clean or cache-controlled build to distinguish a Dockerfile problem from stale build state.
Runtime behavior
Run the image with the same user, command, ports, mounts, and environment shape used in deployment. Check startup, shutdown, health reporting, logs, signal handling, and failure messages. If the image is deployed to Kubernetes, review the container behavior alongside the manifest; YAML or resource settings can create problems that are not visible in the Dockerfile. The YAML troubleshooting guide and Kubernetes resource requests and limits guide can help with that adjacent review.
Release traceability
Record how the image was built, which source revision produced it, and which base-image and dependency versions were used. A repeatable naming and tagging convention helps teams identify an image, but tags alone should not be treated as a complete audit trail. Connect the image to CI results, scan output, and deployment records where your workflow supports it.
Common mistakes
- Copying the entire repository first: This sends unnecessary files into the build context and invalidates dependency-install layers whenever any source file changes.
- Using
latestas an unnoticed dependency: A moving base-image tag can change a build without an obvious Dockerfile diff. Define an update and review process instead. - Putting secrets in build arguments: Build arguments are for configuration of the build, not a secure secret store. Use an appropriate secret mechanism and verify generated artifacts.
- Using shell form for every command: Shell wrapping can affect signal delivery, argument parsing, and process ownership. Use exec form when the application should be the container’s main process.
- Optimizing size before understanding requirements: Removing a shell, certificates, libraries, or time-zone data can break diagnostics or application behavior. Measure and test each reduction.
- Installing packages without cleanup or version discipline: Unreviewed package changes and retained indexes increase image contents and make builds harder to reproduce.
- Adding a weak health check: A command that always succeeds does not demonstrate readiness. Define what healthy means for the service and test that condition.
- Assuming a scanner is the whole security process: Scanning is one control. Secure inputs, least privilege, dependency review, runtime configuration, and patch procedures still matter.
When to revisit
Revisit this Dockerfile checklist before a production release, after changing the language runtime or base image, when build times begin to grow, or when a dependency update changes native modules or generated artifacts. Also review it when moving builders, adding a new CPU architecture, introducing a private package registry, or changing the deployment platform.
Make the review part of the workflow rather than a one-time hardening exercise:
- Build from a clean checkout and record the image identifier.
- Inspect the final layers and confirm that development files and credentials are absent.
- Run the image as the intended user with production-like configuration.
- Test startup, health reporting, graceful shutdown, logs, and required filesystem access.
- Run the team’s image and dependency checks, then document accepted findings and required fixes.
- Compare the result with the previous image for size, build duration, runtime behavior, and traceability.
Keep the checklist near the Dockerfile or in the team’s delivery documentation so it is available during dependency updates and incident reviews. Related workflow checks, such as deployment rollouts and observability coverage, should be reviewed alongside the image rather than after a container reaches production. See the Kubernetes deployment rollout guide and OpenTelemetry instrumentation checklist for those operational follow-ups.