Why does copying the root lockfile into every service image fail?

The obvious way to containerize a service in an Nx workspace is to copy the root package.json and lockfile into the image, run a clean install, then copy in the built output for that one service. It works, but it has two problems that get worse as the workspace grows.

The install layer is shared by every service. Docker caches a layer based on the exact contents of the files copied into it. In an Nx workspace with a single root package.json, the lockfile records dependencies for every app and library. If someone bumps a charting library for the frontend, the lockfile changes, and the cache for the dependency install breaks in every backend image too. Each service then reinstalls everything, even though nothing it uses has changed.

Every image ships packages it never imports. Omitting dev dependencies does not fix this, because the root manifest lists the production dependencies of all projects. A small queue worker ends up carrying the API's ORM, another service's payment SDK, and the frontend's runtime packages. That makes images larger and pulls slower. It also gives the image a bigger attack surface and adds vulnerability scanner findings for code that never runs.

The alternative is a pruned lockfile: each service gets its own package.json and lockfile, generated by Nx from the project graph. These files contain only the dependencies that service actually reaches. This guide is for backend and platform engineers who ship several Node services from one Nx workspace and want builds that are cached per service and images that contain only what each service needs.

How does generatePackageJson produce a pruned lockfile?

When generatePackageJson is enabled on a build executor such as @nx/webpack or @nx/esbuild, Nx does more than bundle. It reads the project graph starting at the application, follows every dependency edge through internal libraries, and records each external npm package it reaches. It then writes a package.json listing only those packages, and a lockfile derived from the root lockfile that keeps only the entries for those packages and their transitive dependencies. Both files land in the build output next to the bundle.

 project graph            dist/apps/orders        image
 ─────────────            ────────────────        ─────
 apps/orders ──┐          main.js                 COPY dist/apps/orders
 libs/db ──────┼─ walk ─▶ package.json   ──────▶  frozen install
 libs/auth ────┘          pruned lockfile         node main.js
 (pg, jose, ...)

The lockfile matters as much as the manifest. A package.json alone holds semver ranges, so an install inside the container would resolve versions again and could pull releases that CI never tested. The pruned lockfile pins exact versions and integrity hashes. That pinning lets the image run npm ci, or the frozen-lockfile mode of Yarn or pnpm. These commands fail when the manifest and lockfile disagree, so drift stops the build instead of reaching production.

Internal libraries: inlined or external

Workspace libraries usually do not appear in the generated manifest because the bundler inlines their source into main.js. Their own npm imports still get collected through the graph walk. If your configuration marks a library as external, for example a buildable library or one you publish to a registry, the runtime must be able to resolve it. That case behaves differently. Open the generated package.json and confirm which case your executor setup produces.

# Build context is the workspace root, after running:
#   npx nx build orders
# with "generatePackageJson": true in the build target options,
# so dist/apps/orders holds main.js, package.json and package-lock.json.
FROM node:20-slim

WORKDIR /app
ENV NODE_ENV=production

# Copy only the generated manifest and pruned lockfile first, so this
# layer is cached until the reachable dependency set actually changes.
COPY dist/apps/orders/package.json dist/apps/orders/package-lock.json ./

# Frozen install: npm ci installs exactly what the lockfile pins and
# fails if package.json and the lockfile disagree, instead of
# re-resolving semver ranges to versions CI never tested.
# (Yarn/pnpm users: use their frozen-lockfile install instead.)
RUN npm ci --omit=dev

# Copy the bundle. Inlined workspace libraries are already inside main.js.
# If any internal library is left external, confirm it is listed in the
# generated package.json and resolvable here before trusting this image.
COPY dist/apps/orders/ ./

USER node
CMD ["node", "main.js"]

A per-service Dockerfile that copies the Nx-generated package.json and pruned lockfile from the build output and runs a frozen npm ci install before adding the bundled main.js.

How do you write a Dockerfile that caches per-service dependencies?

Split the work into two phases. First, run the Nx build for the one service, for example nx build api, somewhere the full workspace and its root install are available. That can be a CI job before docker build, or a builder stage in a multi-stage Dockerfile. The build writes the bundled output together with the generated package.json and pruned lockfile into the app's output directory. That directory is usually under dist/, but check the outputPath in your project configuration.

The runtime stage then needs only that directory, and the order of instructions matters. Copy the generated package.json and lockfile first. Run a frozen, production-only install next, such as npm ci with dev dependencies omitted, or the equivalent frozen-lockfile mode of your package manager. Copy the built application code last. Docker caches each layer based on the files that feed it. The install layer depends only on the two manifest files, so it stays cached across commits that change application code, or that change dependencies used only by other services. It rebuilds only when this service's own dependency graph changes.

This setup has two consequences:

  • The build context must contain the Nx output. A plain docker build on a clean checkout will fail or produce a stale image, so the Nx build has to run first in the pipeline or inside the builder stage.
  • Native modules must be installed in the right environment. Packages with compiled binaries, such as bcrypt or sharp, must be installed in an image whose OS and libc match the runtime. Run the install inside the runtime base image rather than copying node_modules from the host or from a glibc builder into an Alpine (musl) image.
# Assumes CI already ran `npx nx build api` with generatePackageJson enabled,
# so dist/apps/api contains main.js, package.json and package-lock.json.
# Check outputPath in your project config; dist/apps/api is a placeholder.

# Use the same OS/libc as production (Alpine = musl) so native
# modules like bcrypt or sharp are compiled/fetched for this image.
FROM node:20-alpine

WORKDIR /app
ENV NODE_ENV=production

# 1. Copy only the generated manifests. This layer's cache key depends
#    on these two files, which change only when api's own deps change.
COPY dist/apps/api/package.json dist/apps/api/package-lock.json ./

# 2. Frozen, production-only install inside the runtime base image.
#    Stays cached across commits that touch only code or other services.
RUN npm ci --omit=dev && npm cache clean --force

# 3. Copy the built output last; code changes invalidate only this layer.
COPY dist/apps/api/ ./

USER node
CMD ["node", "main.js"]

A runtime Dockerfile that copies the Nx-generated package.json and lockfile, runs a frozen production install in the Alpine runtime image, then copies the built code so the dependency layer stays cached.

How do you verify the pruned package.json before trusting it?

The generated package.json in dist/apps/<service>/ is a prediction built from static import analysis, not a record of what the service loads. Open it after every build that changes dependencies. Compare its dependencies against the packages the service actually touches at runtime. One way to get that list is to start the service locally with Node's module resolution traced or logged, exercise its main code paths, and diff the resolved package names against the pruned manifest.

The more reliable check is to let the image prove itself. Add a CI step that builds the image and runs its real start command, with stub configuration, for a few seconds. Then hit a health endpoint or wait for a clean startup log line. A Cannot find module error then fails the pipeline instead of the first production deploy. Lazily loaded modules only fail when their code path runs, so the smoke test should exercise those paths too.

Static detection reliably misses these cases:

  • require or import() calls with computed paths.
  • Plugins loaded by name from config files, such as loggers, Babel or ESLint presets, and framework adapters.
  • ORM or database drivers chosen at runtime from a connection string.
  • Packages used only by CLI scripts like migrations or seeders.
  • Peer and optional dependencies that hoisting satisfied in the root install but that are absent in an isolated install.

The fix is to declare the missing packages explicitly. You can add them to the app's own package.json, or use the build executor's options for external or additional dependencies. Either way, you now maintain a hand-written list that must track the root lockfile. This is the drift that pruning was meant to remove, so keep the list short and let the smoke test catch omissions.

#!/usr/bin/env bash
# CI smoke test: prove the pruned image can actually start.
# Assumes the project's build target has generatePackageJson enabled
# and that the image's WORKDIR contains the pruned package.json and node_modules.
set -euo pipefail

SERVICE=api
DIST="dist/apps/$SERVICE"
IMAGE="$SERVICE:ci-smoke"

npx nx build "$SERVICE"

# Print the predicted dependency list so reviewers can see what pruning kept.
jq -r '.dependencies | keys[]' "$DIST/package.json" | sort

docker build -t "$IMAGE" -f "apps/$SERVICE/Dockerfile" .

# Run the real start command with stub config (placeholder values only).
cid=$(docker run -d -p 3000:3000 \
  -e NODE_ENV=production \
  -e DATABASE_URL=postgres://ci:ci@db.invalid:5432/ci \
  "$IMAGE")
trap 'docker rm -f "$cid" >/dev/null' EXIT

ok=0
for _ in $(seq 1 15); do
  if curl -fsS  >/dev/null; then ok=1; break; fi
  # Stop waiting if the process already crashed (e.g. Cannot find module).
  [ "$(docker inspect -f '{{.State.Running}}' "$cid")" = "true" ] || break
  sleep 1
done

if [ "$ok" != 1 ] || docker logs "$cid" 2>&1 | grep -q 'Cannot find module'; then
  docker logs "$cid" 2>&1 | tail -n 50
  exit 1
fi

# Static analysis cannot see drivers chosen from a connection string,
# so assert they resolve inside the image explicitly.
docker run --rm --entrypoint node "$IMAGE" -e "require.resolve('pg')"

A CI script that builds the service, prints the pruned dependency list, starts the real image with stub config, fails on a missing health check or a 'Cannot find module' log line, and explicitly checks that a runtime-selected database driver resolves inside the container.

Which package managers and lockfile formats does Nx prune reliably?

Pruning fidelity depends on the parser Nx uses for your lockfile format, not only on the package manager's name. The same tool can write structurally different lockfiles across major versions, and Nx's support for each format changes between releases. Before relying on pruning, check your package manager and lockfile format against the documentation for your installed Nx version. Then build one image and run the frozen install inside it. A frozen install fails when the lockfile and package.json disagree, so it is the quickest way to catch a bad prune.

Package manager Lockfile Frozen install in the image Fidelity questions to confirm
npm package-lock.json npm ci Do workspace-linked packages and peer dependencies survive the prune?
Yarn classic yarn.lock (v1 format) yarn install --frozen-lockfile Are resolutions carried into the pruned package.json?
Yarn modern yarn.lock (Berry format) yarn install --immutable Are patch: and workspace: entries handled? Did you copy .yarnrc.yml and choose a linker that suits containers?
pnpm pnpm-lock.yaml pnpm install --frozen-lockfile Are overrides, patched dependencies and workspace: references preserved?

Pin both Nx and the package manager. Use the packageManager field together with Corepack, or install a fixed version in the base image. This keeps the version that generates the lockfile identical to the version that consumes it. When you upgrade either one, regenerate a pruned lockfile and review its diff before you merge. A parser change can add, drop or re-resolve entries without breaking the build.

If you need pruning outside the stock executors, @nx/js exposes helpers for generating a package.json and a lockfile that you can call from a custom executor. These helpers have moved and changed signature between releases, so check the exported API in your installed version and avoid copying examples written for a different one.

How do Nx affected and image tagging save CI time and cost?

Run your Docker target through nx affected instead of looping over every app. Nx compares the base and head commits, walks the project graph, and returns only the services whose own files or upstream libraries changed. A typo fix in one service's handler rebuilds one image. A change to a shared validation library rebuilds every service that imports it, and no others. This works only if the Docker build is a real Nx target with correct inputs. If the Dockerfile or pruned manifest sits outside what Nx considers part of the project, affected detection will miss changes.

Tag each image with the commit SHA or a content hash of its build inputs, never only latest. Immutable tags let deployments pin exact artifacts, make rollbacks a tag swap, and let CI skip a push when an identical tag already exists in the registry.

The trade-off is that pruning turns one root install into N per-service installs. When a shared library changes, you pay for all N of them.

Illustrative estimate (assumed numbers, not a benchmark): CI install time per commit = affected services × per-service install time. Assume 12 services, 2 affected on a typical commit, and 90 s per install. A typical commit costs 2 × 90 = 180 s. A shared-library change costs 12 × 90 = 1,080 s, compared with perhaps 300 s for a single root install.

That worst case is why a shared package-manager cache mount or a registry proxy matters. Either one reduces the per-service install time on cache hits.

The engineering savings come from scope. You do fewer full-fleet rebuilds. A dependency upgrade redeploys only the services that actually depend on that package. Reviewers can see exactly which images a change will ship.

#!/usr/bin/env bash
# CI step: build and push images only for services Nx marks as affected.
set -euo pipefail

REGISTRY="registry.example.com/acme"   # placeholder registry
BASE="${BASE_SHA:-origin/main}"          # last successful main commit
HEAD="${HEAD_SHA:-HEAD}"
TAG="$(git rev-parse --short=12 "$HEAD")" # immutable tag, never only 'latest'

# Ask the project graph which projects changed (directly or via upstream libs)
# AND define a docker-build target. Dockerfile and pruned manifests must be
# inputs of that target, or changes to them will not be detected.
mapfile -t SERVICES < <(
  npx nx show projects --affected --base="$BASE" --head="$HEAD" \
    --withTarget=docker-build
)

if [ "${#SERVICES[@]}" -eq 0 ]; then
  echo "No affected services; nothing to build."
  exit 0
fi

for svc in "${SERVICES[@]}"; do
  image="$REGISTRY/$svc:$TAG"

  # Skip work if this exact tag is already in the registry (e.g. a CI retry).
  if docker manifest inspect "$image" >/dev/null 2>&1; then
    echo "Skipping $image (already pushed)"
    continue
  fi

  # Each service installs only its pruned dependencies. The Dockerfile should
  # use a BuildKit cache mount for the package manager store so N installs
  # reuse downloads instead of refetching them.
  DOCKER_BUILDKIT=1 docker build -f "apps/$svc/Dockerfile" -t "$image" .
  docker push "$image"
done

A CI script that lists only affected Nx projects with a docker-build target, tags each image with the commit SHA, and skips builds whose tag already exists in the registry.

When should you avoid pruned lockfiles, and what are the alternatives?

Pruning depends on Nx's project graph, which is built from imports it can resolve statically. If a service loads code through computed require paths, plugin directories or configuration-driven module names, those packages never reach the generated package.json. The image builds and then fails at runtime. Services with many native modules gain little from pruning, because the cost is dominated by compiling or fetching platform binaries, and optional platform-specific dependencies are easy to drop by mistake. With a single deployable in the repo, the pruned lockfile is nearly identical to the root one, so the extra build step adds maintenance and saves almost nothing.

Approach Cache behavior Image size Correctness risk Maintenance cost
Pruned lockfile Invalidated only by this service's dependencies Small Missed dynamic imports Moderate: verify generated manifests
Root lockfile Invalidated by any dependency change in the repo Large Low: everything is installed Low
Full bundle, no external deps Invalidated by any source change Smallest install footprint Breaks __dirname and filesystem-layout assumptions High: per-package bundler exceptions
Builder-stage install, copy node_modules Same as the lockfile it installs from Medium Low, if build and runtime base images match Low to moderate

Full bundling deserves the most caution. The output is one large file that is harder to diff and debug. Packages that read templates, migrations or WASM files relative to their own directory break when that layout disappears. Vulnerability scanners also lose the package manifests they rely on to report affected versions, so the scan results tell you less.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to nx docker build lockfile, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.