Dockerfile Best Practices: Build Smaller, Safer, and More Reliable Images
dockercontainersdevopsci-cdsecurity

Dockerfile Best Practices: Build Smaller, Safer, and More Reliable Images

FFilesDownloads Editorial Team
2026-12-04
8 min read

Use this Dockerfile checklist to build smaller, safer images with multi-stage builds, reliable caching, non-root users, health checks, and secret-safe workflow…

A production-ready Dockerfile should do more than start an application: it should create a small, repeatable, inspectable, and appropriately restricted image. This guide provides a reusable checklist for choosing a base image, ordering layers, using multi-stage builds, handling secrets, running as a non-root user, adding health checks, and validating the result locally and in CI.

Overview

A Dockerfile is a build recipe. Each instruction can affect image size, build speed, cache reuse, runtime behavior, and security. The best Dockerfile is not necessarily the shortest one; it is the one whose decisions are explicit and easy to maintain.

Start by defining the application’s runtime requirements. Identify the language version, operating-system libraries, build tools, exposed service port, startup command, writable directories, and required environment variables. Keep build-time values separate from runtime configuration, and document assumptions that another developer or CI system would need to reproduce the image.

A useful production checklist is:

  • Use a deliberate base image rather than relying on an unexamined default.
  • Keep build tools and source files out of the final runtime image when they are not needed.
  • Copy dependency manifests before the rest of the source to improve cache reuse.
  • Exclude local files, credentials, test output, and source-control metadata with .dockerignore.
  • Run the application as a dedicated non-root user where the software supports it.
  • Make the container’s startup command and expected port clear.
  • Build, scan, test, and inspect the image before deployment.

Dockerfile syntax and builder behavior can evolve, so confirm examples against the Docker documentation and the builder used by your project. BuildKit-compatible builds are common, but a CI environment may still require explicit configuration or a compatibility check.

Checklist by scenario

For a new application

Choose a base image that matches the application’s actual runtime rather than choosing the smallest-looking tag automatically. A minimal image may reduce the attack surface and transfer size, but it can also omit debugging tools, shell utilities, certificates, or native libraries your application needs. Test the application in the selected image before adopting it.

Use a specific, reviewed versioning strategy for the base image. A moving tag can simplify updates, while a digest or tightly controlled version can improve reproducibility. Either approach should be paired with a regular update process; pinning an image does not remove the need to review security and compatibility updates.

Keep the Dockerfile readable. Group related package installation and cleanup operations, add comments only where they explain a non-obvious decision, and use an exec-form command for the application process when appropriate:

CMD ["./app", "serve"]

For compiled or dependency-heavy applications

Use a multi-stage Docker build. The first stage contains compilers, package managers, development headers, and source code. The final stage contains only the runtime base, the built artifact, and files required to run it.

A simplified pattern looks like this:

# syntax=docker/dockerfile:1
FROM builder-image:version AS build
WORKDIR /src
COPY dependency-manifest ./
RUN install-dependencies
COPY . .
RUN build-application

FROM runtime-image:version AS runtime
WORKDIR /app
COPY --from=build /src/output ./
USER appuser
EXPOSE 8080
CMD ["./application"]

The names and commands vary by language, but the boundary is consistent: compile in one stage and run from a clean stage. Review the files copied from the build stage so that test fixtures, package caches, and development configuration do not enter the final image.

For faster local and CI builds

Order instructions from relatively stable inputs to frequently changing inputs. Copy dependency manifests first, install dependencies, and copy application source afterward. A source-code change can then reuse the dependency layer when the manifest has not changed.

WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

Use a lockfile when the ecosystem provides one, and make the install command honor it. Avoid invalidating expensive layers unnecessarily by copying the entire working directory before installing dependencies.

Do not treat cache reuse as a reason to preserve stale dependencies. When dependency manifests, base images, build arguments, or relevant tool versions change, rebuild in a way that tests the new inputs. In CI, balance speed with a periodic clean build so hidden cache assumptions do not go unnoticed.

For services handling credentials

Never copy a secret into the build context merely because a command needs it. Do not place passwords, API keys, private certificates, or tokens in Dockerfile ENV or ARG instructions when they could become visible through image history, metadata, logs, or cached layers.

Use the secret mechanism supported by your builder and CI system. With BuildKit-style syntax, the pattern may look like this:

# syntax=docker/dockerfile:1
RUN --mount=type=secret,id=registry_token \
    ./download-private-dependency.sh /run/secrets/registry_token

Pass the secret through the build command or CI integration rather than committing its value. Verify that the command does not echo the secret and that the resulting image contains no secret file. Build secrets and runtime secrets solve different problems: a credential needed to build an artifact should not automatically be available to the running container.

For internet-facing services

Create or select a dedicated non-root user and ensure the application files have suitable ownership and permissions. A non-root process does not make an image secure by itself, but it limits the impact of some application-level mistakes.

Add a health check only when you can define a meaningful test. A health check should verify that the service is able to perform the basic operation required by its consumers, not merely that a process exists. Consider the endpoint’s authentication requirements, startup time, network dependencies, and the difference between readiness and liveness.

HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
  CMD ["/app/healthcheck"]

Coordinate the Dockerfile health check with the orchestrator or hosting platform. If the platform already manages readiness and liveness separately, duplicating a weak check can create confusing restarts.

What to double-check

Build context and ignored files

Review .dockerignore before the first build. It commonly excludes .git, local dependency directories, build output, editor files, test artifacts, environment files, and private keys. The exact list depends on the project, so confirm that no file required by the build is excluded accidentally.

Runtime assumptions

Run the built image with the same important environment variables, mounted directories, user permissions, and network conditions used in deployment. Test the container’s actual startup command rather than replacing it with an interactive shell. Confirm that it handles termination signals and writes only to directories intended to be writable.

Image contents

Inspect the final image rather than assuming the multi-stage boundary worked. Look for source maps, package-manager caches, compilers, shell history, test data, configuration files, and credentials. An image inspection tool or a vulnerability scanner can help identify unexpected packages, but treat scanner output as a prompt for review rather than an automatic substitute for context.

Application and configuration files

Keep environment-specific configuration outside the image where practical. An image should be reusable across environments, with deployment-time configuration supplying differences such as service URLs, log levels, and credentials. For structured configuration, validate the file format before the image build; a YAML validator or JSON formatter can catch syntax problems that otherwise appear only during startup. See the YAML validators and formatters guide or the JSON formatter and validator guide for related workflows.

Documentation and maintenance

Document the build command, required arguments, expected port, health endpoint, and local run instructions. A concise README reduces the chance that developers bypass the intended workflow. The Markdown editor and preview workflow can help when maintaining project documentation.

Common mistakes

  • Using one large image for both build and runtime: This leaves compilers and development dependencies in production. Use multi-stage builds when the runtime does not need them.
  • Copying everything before installing dependencies: Frequent source changes invalidate the dependency layer. Copy manifests first, then install, then copy source.
  • Using latest without a review process: A moving tag can change the result of a later build. Choose a versioning approach that fits your release and update workflow.
  • Adding secrets through build arguments: Build arguments are not a secure secret store. Use builder-supported secret mounts or an equivalent CI mechanism.
  • Running as root by default: Check whether the base image and application support a dedicated user, then test file permissions and startup behavior.
  • Adding a meaningless health check: A command that always succeeds does not establish service health. Test a useful application path or omit the check until one can be defined.
  • Using shell-form commands without considering signals: Process handling can differ when a shell becomes the container’s process. Prefer an appropriate exec-form command and verify graceful shutdown.
  • Trusting a successful build too much: A build proves that an image was created, not that it starts correctly, serves traffic, contains no unexpected files, or works with production configuration.

When to revisit

Review a Dockerfile whenever the application changes its language version, dependency manager, build output, startup command, port, filesystem requirements, or deployment platform. Revisit it before a significant release, after changing CI caching, and whenever a base image or builder is updated.

Use a repeatable review workflow:

  1. Build the image with the project’s normal command and record the tag or digest used for testing.
  2. Run the container with representative configuration and verify startup, requests, logs, shutdown, and health behavior.
  3. Inspect image layers and scan the final image using the security tooling available to your team.
  4. Test a clean build without relying on an old local cache, then compare the result with the normal cached build.
  5. Review the Dockerfile and .dockerignore for newly introduced files, credentials, permissions, and unnecessary packages.
  6. Update the documentation when a command, environment variable, port, health check, or build requirement changes.

Keep this checklist with the project and apply it when workflows or tools change. For related development hygiene, a pre-commit workflow can automate formatting, linting, tests, and secret checks; see the pre-commit tools guide. The goal is not to make every Dockerfile identical. It is to make each image’s inputs, contents, runtime permissions, and validation steps understandable enough to review and reproduce.

Related Topics

#docker#containers#devops#ci-cd#security
F

FilesDownloads Editorial Team

Developer Tools Editor

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.