Build Docker Images That Are Fast, Reproducible and Safer to Ship

Tim Rabbetts | November 21, 2026

A Dockerfile can be perfectly functional and still be expensive to maintain. It may rebuild dependencies whenever a source file changes, ship compilers and test tools into production, copy private credentials into image layers, or produce a different image from the same commit a week later.

Those problems matter beyond build speed. Slow builds reduce feedback during development and consume more CI time. Large images take longer to transfer and contain more components that need patching. Uncontrolled base-image tags make it harder to reproduce a release or explain exactly what was deployed.

This guide develops a practical pattern for building application images that are faster to rebuild, smaller to run and easier to audit. The examples use a small Node.js service, but the principles also apply to PHP, Python, Go, Ruby and compiled applications.

Prerequisites and the goal

You will need Docker with BuildKit support, a working application, a package lock file and a basic understanding of Dockerfile instructions. The examples assume a project with files similar to these:

.
├── Dockerfile
├── .dockerignore
├── package.json
├── package-lock.json
├── src/
│   └── server.js
└── test/

The aim is not to create the smallest possible image at any cost. An aggressively minimal image can be awkward to debug or incompatible with native dependencies. A better target is a deliberately selected runtime image containing everything the application needs, and little that it does not.

Understand what invalidates Docker’s cache

Docker builds an image in layers. Each Dockerfile instruction contributes to the build result, and when a layer changes, later layers generally need to be rebuilt. Docker’s documentation recommends placing expensive, stable operations before frequently changing source files, while keeping the build context small. See the official cache optimisation guidance. ([docs.docker.com](https://docs.docker.com/build/cache/optimize?utm_source=openai))

Consider this common structure:

FROM node:22
WORKDIR /app

COPY . .
RUN npm ci

CMD ["node", "src/server.js"]

It works, but a change to any file in the build context can invalidate the COPY layer. That forces npm ci to run again, even when the dependency manifests have not changed.

Copy the manifests first, install dependencies, and only then copy the application source:

FROM node:22
WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci

COPY src ./src

CMD ["node", "src/server.js"]

Now a change under src/ can reuse the dependency-install layer. The exact saving depends on your package manager, network and project size, so measure it with your own builds rather than assuming a particular improvement.

Keep the dependency installation deterministic. For npm projects, npm ci is intended for clean, lock-file-based installs and should fail if the lock file does not match package.json. Do not silently regenerate the lock file inside an image build; update it as a reviewed source-control change instead.

Use a .dockerignore file deliberately

The build context is the set of files sent to the builder. Sending a whole repository can make builds slower and can accidentally expose material to build steps. A .dockerignore file excludes files from that context, much like .gitignore, although the rules serve a different purpose.

node_modules
npm-debug.log
.git
.gitignore
Dockerfile*
.dockerignore
.env
.env.*
coverage
dist
tmp
*.log

There is an important caveat: ignoring a file means it cannot be copied from the build context. If a later Dockerfile instruction expects a generated file, documentation file or certificate that is excluded here, the build will fail. Conversely, never rely on .dockerignore as your only secret-protection mechanism. A secret should not be present in the build context in the first place.

Check the size of the context in the build output. If it is unexpectedly large, look for dependency directories, local caches, test artefacts, virtual environments, media files and repository history.

Separate build dependencies from runtime dependencies

A single-stage image often contains everything required to compile, test and run an application. That may include compilers, header files, Git, test frameworks and development dependencies that are irrelevant once the application is ready to start.

Multi-stage builds solve this by using more than one FROM instruction. Build tools remain in an earlier stage, while the final stage receives only the files needed at runtime. Docker documents this pattern in its multi-stage build documentation. ([docs.docker.com](https://docs.docker.com/build/building/multi-stage/?utm_source=openai))

For a Node.js service, one practical version is:

# syntax=docker/dockerfile:1

FROM node:22 AS dependencies
WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci

FROM dependencies AS test
WORKDIR /app

COPY src ./src
COPY test ./test
RUN npm test

FROM node:22-slim AS production
WORKDIR /app
ENV NODE_ENV=production

COPY package.json package-lock.json ./
RUN npm ci --omit=dev

COPY --from=test /app/src ./src

USER node
EXPOSE 3000

CMD ["node", "src/server.js"]

This example uses three stages:

  • dependencies installs the complete dependency tree needed by tests and the application.
  • test copies the source and test files, then makes the test suite a build gate.
  • production starts from a smaller runtime variant and installs only production dependencies.

The production stage does not copy the test directory, package-manager cache, source-control metadata or build tools. The COPY --from=test instruction takes only the application source from the earlier stage.

Do not assume that a smaller image is automatically safer. A slim or Alpine-based image can introduce compatibility differences, especially for native modules, C libraries, debugging tools and certificate stores. Test the actual production image, including startup, outbound HTTPS, file permissions, graceful shutdown and health checks.

Use cache mounts for package downloads

Layer caching is useful when the Dockerfile instruction and its inputs remain unchanged. A cache mount is different: it preserves a package manager’s download cache even when the surrounding layer must be rebuilt. Docker documents cache mounts for npm, Composer, pip, Go, Apt and other tools. ([docs.docker.com](https://docs.docker.com/build/cache/optimize/?utm_source=openai))

For npm, the dependency stage can use a cache mount like this:

# syntax=docker/dockerfile:1

FROM node:22 AS dependencies
WORKDIR /app

COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
    npm ci

The mount is intended as a performance aid, not as a source of correctness. The build must still succeed if the cache is empty, incomplete or removed. Never store application configuration or credentials in a package-manager cache and assume that a cache mount is an encrypted secret store.

In CI, the builder may be ephemeral, so its local cache disappears after the job. BuildKit can export and import cache data through a registry or another supported backend. A simplified command looks like this:

docker buildx build \
  --cache-from type=registry,ref=registry.example.com/team/app:buildcache \
  --cache-to type=registry,ref=registry.example.com/team/app:buildcache,mode=max \
  --tag registry.example.com/team/app:commit-sha \
  --push .

Keep the cache image separate from deployable application tags. It is an optimisation artefact, not a release. Treat it as disposable and avoid granting production systems unnecessary permission to pull or push it.

Never bake build secrets into image layers

Passing a token through ARG or ENV is unsafe for build credentials. Those values can remain visible through image metadata, layer history or intermediate images. Docker recommends secret mounts and SSH mounts instead of build arguments and environment variables for sensitive build inputs. See the build secrets documentation. ([docs.docker.com](https://docs.docker.com/build/building/secrets?utm_source=openai))

For example, suppose a private package registry requires an npm configuration file. Pass it temporarily:

# syntax=docker/dockerfile:1

FROM node:22 AS dependencies
WORKDIR /app

COPY package.json package-lock.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
    npm ci
docker build \
  --secret id=npmrc,src="$HOME/.npmrc" \
  --tag example-app:local .

The secret is mounted only for the relevant RUN instruction and is not copied into the resulting image. You still need to consider what the package manager writes to logs, caches or generated files. Use a narrowly scoped token, rotate it regularly and verify that the final image does not contain credentials.

For private Git dependencies, an SSH mount may be more suitable than copying a private key into the image. The same principle applies: expose credentials only to the command that needs them, and ensure the output does not retain them.

Pin base images, but plan updates

Using a floating tag such as latest makes an image convenient to start but difficult to reproduce. The tag can point at a different image later, which may change operating-system packages, language behaviour or native-library compatibility.

A version tag is clearer:

FROM node:22.14.0-slim

For stronger reproducibility, pin the tag to a digest:

FROM node:22.14.0-slim@sha256:replace-with-the-reviewed-digest

A digest identifies the exact image content, but it also means security updates will not arrive automatically. Docker’s guidance describes this trade-off and recommends pairing pinned references with a controlled update process, such as automated pull requests and regular image review. ([docs.docker.com](https://docs.docker.com/build/building/best-practices/?trk=article-ssr-frontend-pulse_little-text-block&utm_source=openai))

A workable policy is to record the digest in the Dockerfile, scan or inspect the proposed update, run the application and integration tests, then merge the digest change as a normal reviewed commit. Do not copy a digest from an untrusted forum post or assume that a tag and digest belong to the same image without verifying them through your registry tooling.

Run the application without root

Containers default to the root user unless the image or runtime configuration changes it. If the application does not need elevated privileges, run it as a non-root user. Docker recommends using USER for this purpose and notes that explicit user and group IDs can be useful where file ownership must be predictable. ([docs.docker.com](https://docs.docker.com/build/building/best-practices/?utm_source=openai))

The official Node image includes a node user, so the production stage can use:

WORKDIR /app
COPY --chown=node:node package.json package-lock.json ./
RUN npm ci --omit=dev

COPY --chown=node:node src ./src

USER node
CMD ["node", "src/server.js"]

Make sure the application writes only to directories that the user can access. Prefer stdout and stderr for logs rather than writing log files inside the container. If the application needs temporary files, use a known writable directory and document its lifecycle.

Running as non-root inside the image does not remove every host-level risk. Review mounted directories, Linux capabilities, device access, privileged mode, host networking and the permissions granted to the Docker daemon. On Linux, rootless Docker can run the daemon and containers as a non-root user, but it has prerequisites and feature limitations that should be checked before adopting it broadly. ([docs.docker.com](https://docs.docker.com/engine/security/rootless/?utm_source=openai))

Use exec-form commands and build checks

Use JSON-array syntax for CMD and ENTRYPOINT when starting the main process:

CMD ["node", "src/server.js"]

This avoids an unnecessary shell and helps signals reach the application process directly. That matters when the container receives a stop request and the application needs to close connections or finish in-flight work.

Recent Docker build tooling includes Dockerfile checks. Running the following validates the build configuration without producing an image:

docker build --check .

The checks can identify issues such as relative work directories, undefined variables, suspicious secret usage in ARG or ENV, ignored files that are later copied, and shell-form commands where JSON syntax is recommended. Docker documents the available checks and the option to make violations fail the build. ([docs.docker.com](https://docs.docker.com/build/checks/?utm_source=openai))

You can also make the Dockerfile fail on check violations:

# syntax=docker/dockerfile:1
# check=error=true

Be cautious when turning warnings into errors. Build rules can evolve, so review the syntax version and treat skipped checks as documented exceptions rather than a blanket escape hatch.

A practical review checklist

Before merging a Dockerfile, ask the following questions:

  1. Does the build context exclude dependency directories, local configuration, logs and repository metadata?
  2. Are lock files copied before application source so dependency layers can be reused?
  3. Are build, test and runtime concerns separated into named stages?
  4. Does the final image contain only production dependencies and runtime artefacts?
  5. Are package downloads accelerated with cache mounts without relying on the cache for correctness?
  6. Could any token, password, private key or registry credential remain in a layer or image history?
  7. Is the base image selected from a trusted source and updated through a reviewable process?
  8. Is the base reference reproducible enough for your release requirements?
  9. Does the process run as a non-root user with only the filesystem access it needs?
  10. Does the image pass tests, startup checks and docker build --check in CI?

What good looks like

A well-engineered Docker image is not merely small. It has a clear boundary between build inputs and runtime inputs, a cache-friendly instruction order, an explicit update policy and a testable security posture.

Start with the changes that pay off immediately: add .dockerignore, move dependency manifests before source copies and remove floating base tags. Then introduce multi-stage builds, non-root execution and secret mounts. Finally, make the workflow repeatable in CI with imported build cache, image scanning, automated base-image updates and build checks.

The result is a Docker workflow that gives developers fast local feedback while giving reviewers a clearer answer to the important production question: exactly what is this image, what went into it, and why should we trust it?