A production-ready Dockerfile should make an image predictable, small enough to ship efficiently, and safe to run with limited privileges. This checklist explains how to choose a base image, order instructions for useful build cache reuse, apply multi-stage builds, run as a non-root user, handle signals correctly, and verify the result before release.
Overview
A Dockerfile is both a build recipe and part of your application’s operational interface. Every instruction affects build time, image contents, debugging, security review, or runtime behavior. The goal is not to make every image as small as possible at any cost; it is to make the image contain only what the application needs while preserving reliable diagnostics and repeatable builds.
Start by separating three concerns:
- Build inputs: compilers, package managers, headers, test tools, and source files.
- Runtime inputs: the executable, application assets, shared libraries, certificates, and configuration defaults.
- Operational behavior: the user, working directory, exposed port, health check, and process launched by the container.
A multi-stage build keeps those concerns separate. A builder stage can install the toolchain and compile the application, while the final stage copies only the generated artifact and required runtime files. This approach usually improves reviewability as well as image size.
For related workflow practices, see the CMake project structure guide when containerizing compiled applications, and the REST API debugging workflow when testing a containerized service.
Checklist by scenario
For every Dockerfile
- Choose an intentional base image. Use an image that matches the runtime you need, and prefer a maintained, minimal variant when it provides the libraries and debugging tools your service requires. Pin the base image by a deliberate version or digest strategy rather than silently accepting an unexpected change during a build.
- Add a focused build context. Create a
.dockerignorefile that excludes version-control metadata, local dependencies, build output, test artifacts, secrets, editor files, and unrelated documentation. A smaller context reduces accidental copying and can make builds easier to reason about. - Use a predictable working directory. Set
WORKDIRbefore copying application files. This avoids long, fragile paths and makes later instructions clearer. - Order instructions for cache reuse. Copy dependency manifests before the rest of the source when the package manager supports it. Install dependencies in one layer, then copy frequently changing application code. Changes to a source file should not invalidate an expensive dependency step unnecessarily.
- Make the process explicit. Prefer an executable form of
ENTRYPOINTorCMDwhen the application should receive operating-system signals directly. Avoid relying on an interactive shell to launch the service. - Run with reduced privileges. Create or select a dedicated non-root user after installation steps that require elevated permissions. Confirm that the user can read application files and write only to directories that genuinely need writable access.
For a web service or API
A typical runtime image should contain the server, application code, production dependencies, certificates where required, and a clear startup command. Document the container port with EXPOSE, but remember that this instruction is metadata rather than a firewall rule or a host port mapping.
Use a health check only when you can define a meaningful test. A useful check verifies that the process is responsive through a local endpoint or an application-specific command. It should not depend on a tool that is absent from the final image, and it should not turn a temporary downstream dependency failure into an ambiguous container failure unless that is the intended readiness policy.
Keep environment-specific values outside the image. Configuration supplied at deployment time is easier to change than values baked into layers. Never copy credentials, private keys, or local environment files into the build context.
For a compiled application
Use a builder stage with the compiler and development dependencies, then copy the resulting binary into a runtime stage. If the binary depends on shared libraries, identify those dependencies deliberately rather than assuming that a smaller base image can execute it. Include required certificate bundles for outbound TLS connections, and test the final stage independently of the builder.
For example, a generic Go service can use this pattern:
FROM golang:1 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/server ./cmd/server
FROM scratch
COPY --from=build /out/server /server
USER 65532:65532
ENTRYPOINT ["/server"]
The exact base image and user should be chosen for the application. A minimal final stage is useful only if the service does not require shell utilities, certificates, timezone data, or dynamically linked libraries. When those requirements exist, use a suitable runtime base instead of forcing a smaller but incomplete image.
For a JavaScript or TypeScript service
Install production dependencies separately from development dependencies when the package manager and project layout support it. Copy the lockfile with the manifest, use the package manager’s lockfile-respecting install mode, and avoid copying local node_modules from the host. A common multi-stage structure is: dependency stage, build stage, and runtime stage. The runtime stage should contain compiled output and production dependencies, not the full toolchain or source tree unless runtime behavior requires them.
Use the same Node.js major version assumptions in local development, CI, and the image. Version drift is a workflow problem as much as a runtime problem; it can produce an image that builds successfully but behaves differently from developer tests.
Before-and-after Dockerfile comparison
This first example is functional but creates avoidable problems:
FROM ubuntu:latest
COPY . /app
WORKDIR /app
RUN apt-get update
RUN apt-get install -y nodejs npm
RUN npm install
RUN npm run build
CMD npm start
The base tag can move unexpectedly, package metadata is left behind, all source and local files enter the context, development dependencies may remain in the runtime image, and the shell-form command can complicate signal handling. The cache is also poorly arranged: changing any source file invalidates dependency installation.
A more deliberate pattern looks like this:
FROM node:20 AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
RUN npm prune --omit=dev
FROM node:20-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build --chown=node:node /app/package.json /app/package-lock.json ./
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
This version is still an example rather than a universal template. Adjust the output directory, runtime command, native dependencies, and base-image version to the project. The important decisions are visible: dependency manifests are copied first, the build toolchain stays in an earlier stage, production dependencies are selected intentionally, ownership is assigned during copying, and the application runs as a dedicated user.
What to double-check
- Reproducibility: Is there a lockfile, and does the install command honor it? Are base-image updates deliberate and reviewable? Can CI rebuild the image without files from a developer’s machine?
- Secrets: Search the Dockerfile, build arguments, context, and image history for tokens, keys, certificates, and environment files. Build arguments and image layers should not be treated as secure secret storage.
- Ownership and permissions: Inspect the final image as the runtime user. Confirm that logs, temporary files, caches, and application data use appropriate writable locations.
- Signals and shutdown: Send a termination signal to a running container and verify that the application stops cleanly within the expected period. If a wrapper script is necessary, use proper signal forwarding or an init strategy appropriate to the runtime.
- Health behavior: Test the health check when the service is healthy, starting, and unable to serve requests. Make its timeout and retry behavior match the application rather than copying defaults without review.
- Image contents: Use an image inspection tool to check layers, large files, package lists, compilers, test fixtures, and unexpected source files. Size alone is not the only measure; unnecessary capability and unclear provenance also matter.
When diagnosing an oversized image, compare stages and inspect the largest layers first. When diagnosing a slow build, determine whether the delay is dependency installation, source compilation, network access, or cache invalidation. BuildKit features can improve caching and secret handling, but they do not remove the need to keep the Dockerfile’s inputs explicit.
Common mistakes
- Using
latestby default: A moving tag makes it harder to explain why two builds differ. Choose an update policy that balances repeatability with planned security updates. - Combining unrelated concerns into one giant command: Long shell commands are difficult to review and debug. Combine operations when doing so reduces temporary package metadata, but keep distinct decisions readable.
- Deleting files in a later layer: Removing a secret or large artifact after copying it may leave it in an earlier layer. Prevent sensitive or unnecessary files from entering the context or stage in the first place.
- Running as root because permissions are inconvenient: Fix ownership during the build, choose an appropriate writable directory, or revise the application’s file behavior instead of making the entire process privileged.
- Assuming smaller always means better: A stripped image that lacks certificates, debugging information, shared libraries, or a usable shell can increase operational cost. Minimize deliberately, then test real workflows.
- Ignoring the final stage during testing: A build can pass while the runtime image lacks a file, user, library, or environment variable. Start and exercise the exact image that will be deployed.
When to revisit
Review a Dockerfile whenever the application’s runtime, dependency manager, build process, or deployment environment changes. Useful triggers include upgrading the language runtime, changing package managers, adding native modules, moving from a single-stage build to a release image, or introducing a new CI cache strategy.
Set a recurring maintenance point around your normal planning cycle to inspect base-image versions, lockfiles, operating-system packages, image size, and vulnerability findings. The exact interval depends on the application’s risk and release cadence; the important practice is to make the review owned and repeatable rather than waiting for a failed deployment.
Before merging a Dockerfile change, run this short final sequence:
- Build from a clean context with the intended cache settings.
- Inspect the final image and compare its size and layers with the previous version.
- Run the container as its configured non-root user.
- Exercise the health check, startup path, shutdown path, and one representative request or job.
- Confirm that no secrets or unnecessary build tools are present.
- Record the base-image and dependency update assumptions in the project’s normal maintenance workflow.
This checklist is also useful alongside a broader debugging process. For API containers, connect runtime checks with the OpenAPI 3.1 guide; for regressions introduced by image or dependency changes, use a repeatable Git bisect workflow. Revisit the Dockerfile when those inputs change, not only when the image fails to build.