A good Dockerfile can reduce build time, keep images lean, and make container behavior easier to review. This practical checklist shows how to improve layer order, control the build context, use multi-stage builds and cache mounts, run as a non-root user, pin important inputs, configure health checks, and verify the result before deployment.
Overview
Docker image quality is shaped by more than the final image size. A production-ready Dockerfile should also make efficient use of the build cache, avoid copying unnecessary files, separate build-time dependencies from runtime dependencies, and establish safe defaults for the process inside the container.
These goals sometimes compete. A very small image may be harder to debug, while aggressive caching can preserve outdated dependencies if inputs are not ordered carefully. Treat the Dockerfile as a reproducible build definition: make inputs explicit, keep stages focused, and confirm that the runtime image contains only what the application needs.
The following before-and-after example illustrates the main improvements. The exact package manager and commands will vary by language and framework, but the structure is broadly reusable.
| Area | Less effective pattern | Improved pattern |
|---|---|---|
| Build context | Copies the whole repository into the build. | Uses a focused .dockerignore file. |
| Dependency caching | Copies source files before installing dependencies. | Copies dependency manifests first, then installs. |
| Image contents | Uses one image for compiling and running. | Uses a multi-stage build with a smaller runtime stage. |
| Permissions | Runs the application as the default root user. | Creates and selects a dedicated non-root user. |
| Configuration | Bakes environment-specific values into the image. | Supplies runtime configuration at deployment time. |
Checklist by scenario
When builds are slow
- Start with the build context. Add a
.dockerignorefile and exclude source-control metadata, local dependency directories, test output, logs, editor files, documentation that is not needed during the build, and environment files containing local secrets. A smaller context reduces unnecessary transfer and prevents accidental inclusion. - Order layers from stable to volatile. Copy lockfiles or dependency manifests before application source. Install dependencies in that layer, then copy the source. Changes to a source file should not invalidate an otherwise unchanged dependency layer.
- Combine related package operations carefully. Update package indexes and install packages in the same
RUNinstruction when the package manager requires an index. Remove package lists in that same instruction where appropriate so temporary metadata does not remain in the layer. - Use BuildKit cache mounts for repeatable package downloads. For example, a build step may use
RUN --mount=type=cache,target=/path/to/package-cache .... Choose the cache path for the package manager in use, and confirm that the CI builder supports the syntax before relying on it. - Measure the slow layer instead of guessing. Review build output and compare timings before and after each change. A cache improvement is useful only if the relevant inputs are stable and the cache is available in the environments where builds run.
When images are too large
- Use a multi-stage Docker build. Keep compilers, development headers, test tools, and package managers in a build stage. Copy only the compiled artifact, application bundle, or production dependency set into the runtime stage.
- Select a base image deliberately. Consider the application’s runtime requirements, compatibility, debugging needs, update process, and organizational image policy. A minimal image is not automatically the best choice if it prevents basic diagnosis or lacks required system libraries.
- Copy specific paths. Prefer explicit
COPYinstructions over copying the entire build workspace into the final stage. This makes the runtime contents easier to review and reduces accidental inclusion of tests, credentials, and development files. - Keep cleanup in the same layer. Deleting a file in a later layer does not necessarily remove the data from earlier layers. Avoid creating unwanted files in the first place, or create and remove temporary files within one build instruction.
When hardening a container
- Run as a dedicated non-root user. Create the user and group in the runtime stage, assign ownership only where needed, and switch with
USER. Verify that the application can write to its required directories without broad permissions. - Do not bake secrets into the image. Avoid putting credentials in
ARG,ENV, copied files, or shell history. Supply secrets through the deployment platform’s supported mechanism and review build logs for accidental disclosure. - Pin important image inputs. Use a deliberate versioning approach for base images and dependencies. Tags are convenient, but they can move; stronger pinning can improve reproducibility when balanced with a process for updates and vulnerability response.
- Set a clear entrypoint and command. Ensure the main process receives signals correctly and that the container does not depend on an interactive shell. If a wrapper script is required, make its error handling and signal behavior explicit.
- Add a useful health check where the platform uses it. The check should test a meaningful local condition, use a lightweight command, and reflect actual readiness rather than merely confirming that a process exists. Do not add a health check that duplicates an external monitoring system without understanding how failures will affect deployment behavior.
When preparing CI/CD
- Build from a clean, predictable context and make the Dockerfile’s required files explicit.
- Test the image as the same user and with similar environment assumptions to production.
- Scan the built image and its dependencies using the security tooling approved for your project. Treat findings as inputs for review rather than assuming every result has the same severity or remediation path.
- Use immutable build outputs or recorded image references where your deployment process requires reliable rollback.
- Keep the Dockerfile reviewable. A shorter file is not always better; clear stages, comments for non-obvious decisions, and explicit commands help future maintainers.
For related workflow checks, see the GitHub Actions Workflow Validator Guide. If the container serves an API, the OpenAPI Validator Guide can help keep the application contract aligned with deployment tests.
What to double-check
- Runtime completeness: Start a container from the final stage, not the build stage, and verify that the application starts without development tools or files that were present only during compilation.
- Port and bind behavior: Confirm the application listens on the expected interface and port. Declaring an exposed port documents intent but does not replace the application’s runtime configuration or the platform’s service mapping.
- File ownership: Test read, write, temporary-file, upload, and log paths as the non-root user. Permission errors often appear only after a feature is exercised.
- Cache correctness: Change a dependency manifest and confirm that the dependency-install layer is rebuilt. Then change only application source and confirm that stable dependency work remains cached.
- Configuration boundaries: Inspect the image history and filesystem for environment files, tokens, private keys, test fixtures, and local configuration.
- Signal and shutdown behavior: Stop the container and confirm the application exits cleanly. This is especially important when an entrypoint script starts child processes.
- Scan and update workflow: Record how the team evaluates base-image and dependency findings, who owns updates, and how a rebuilt image is promoted.
A Dockerfile review is easier when supported by small, focused utilities. For example, JSON configuration can be checked with the JSON Formatter and Validator Guide, while API requests used in container smoke tests can be prepared with the cURL Command Builder Guide.
Common mistakes
- Copying the repository before installing dependencies: This makes ordinary source edits invalidate an expensive layer.
- Using
latestas an update strategy: A moving tag can change unexpectedly, while a permanently fixed version can become stale. Define a review and update process instead. - Assuming a smaller image is automatically safer: Security depends on the complete software supply chain, configuration, permissions, runtime behavior, and update process.
- Running as non-root without testing: The setting is valuable only if application directories and startup behavior support it.
- Putting build secrets in arguments: Build arguments can be visible through build metadata or logs. Use an appropriate secret-delivery mechanism instead.
- Adding a misleading health check: A command that always succeeds, depends on an unavailable tool, or checks the wrong endpoint can hide failures or trigger unnecessary restarts.
- Optimizing without a baseline: Record image size, build duration, cache behavior, startup time, and scan results before making changes. Otherwise, it is difficult to tell which trade-offs helped.
When to revisit
Review a Dockerfile whenever the application’s build system, base image, package manager, deployment platform, or CI workflow changes. It is also worth revisiting when builds slow down, an image scan reports a new finding, a deployment fails after moving to a new runtime, or a service needs a production hardening review.
As a routine, schedule a quarterly rebuild against the project’s approved current inputs, then compare the result with the previous image. Review the Dockerfile syntax and BuildKit features your builders support, confirm that pinned inputs still have an update path, and repeat the security scan. Before seasonal planning or larger release cycles, use the checklist below:
- Inspect and update
.dockerignore. - Confirm stable-first layer ordering and cache behavior.
- Verify that the final stage contains only runtime requirements.
- Run the image as a non-root user and test writable paths.
- Check base-image and dependency update decisions.
- Test startup, shutdown, health checks, and configuration injection.
- Scan the rebuilt image and document unresolved findings.
- Record the measured build and image-size changes for the next review.
Start with one service rather than rewriting every Dockerfile at once. Establish a baseline, apply the highest-impact change, test the final runtime image, and keep the review notes with the code. That approach turns Dockerfile optimization into a repeatable part of the developer workflow instead of a one-time cleanup task.