What is an Nx pruned lockfile build, and why does copying the root lockfile bloat images?

A pruned lockfile build is a pattern in which Nx writes a package.json and a matching lockfile into the app's build output directory. Both files list only the third-party packages that the app's compiled code imports, and the lockfile keeps the versions already resolved at the workspace root. In this guide, the generatePackageJson option on the build target produces these files. The Docker image then copies the build output and runs a production install against those two files. Nothing else from the monorepo enters the image.

The naive approach copies the root package.json and lockfile, or the whole workspace node_modules, into the image. In an integrated monorepo the root manifest describes every project, so this choice has three costs:

  • Image size. The install pulls in every project's dependencies. A small API service ends up carrying frontend frameworks, bundlers, test runners, linters, and database drivers that only another service uses.
  • Vulnerability surface. Each extra package is one more thing for scanners to flag and for you to triage. Many findings will be in code your service never loads, but you still have to prove that for each one.
  • Cache invalidation. The install layer depends on the root lockfile. When any team bumps any dependency, every service image reinstalls from scratch, even services whose dependencies did not change.

Use this pattern if you are a backend or platform engineer shipping Node services from an integrated Nx monorepo with a single root lockfile.

How does generatePackageJson work with the project graph and lockfile pruning?

When you enable generatePackageJson, Nx stops treating the root package.json as the app's dependency list. It uses the project graph instead. During the build, Nx follows the app's imports and the libraries it depends on, and collects the external npm packages actually reached. It writes only those packages, at the versions declared in the root manifest, to a new package.json in the build output.

In a project.json, this usually means adding "generatePackageJson": true to the options of the app's build target, whether that target uses the webpack or esbuild executor. In inferred-target setups, you set it in the bundler plugin options instead. The option name and its location have changed across Nx versions and executors, so check the docs for your setup before copying it.

Nx then derives the pruned lockfile from the root lockfile, whether that is package-lock.json, yarn.lock or pnpm-lock.yaml. It keeps the entries for the generated manifest's packages and their full transitive closure, and drops everything else. Resolved versions and integrity data stay as they were, so npm ci (or its equivalent) in the container installs the same tree your tests ran against.

Workspace libraries imported through TypeScript path aliases such as @org/auth are compiled into main.js. They should never appear as npm dependencies. If one does, a library is probably being resolved as an external package rather than bundled.

 root lockfile ──┐
                 ├──► nx build api ──► dist/apps/api/
 project graph ──┘                     ├── main.js
                                       ├── package.json      (pruned)
                                       └── package-lock.json (pruned)
                                                 │
                                                 ▼
                                    Docker runtime stage: npm ci
{
  "name": "api",
  "projectType": "application",
  "sourceRoot": "apps/api/src",
  "targets": {
    "build": {
      "executor": "@nx/esbuild:esbuild",
      "outputs": ["{options.outputPath}"],
      "options": {
        "platform": "node",
        "outputPath": "dist/apps/api",
        "main": "apps/api/src/main.ts",
        "tsConfig": "apps/api/tsconfig.app.json",
        "format": ["cjs"],
        "bundle": true,
        "generatePackageJson": true
      },
      "configurations": {
        "production": {
          "minify": true
        }
      }
    }
  }
}

Illustrative project.json build target with generatePackageJson enabled, so the build writes a minimal package.json and a pruned lockfile next to main.js. Confirm the option name and location for your Nx version and executor.

How do you write a multi-stage Dockerfile for an Nx Node app?

The Dockerfile has two stages. The builder stage starts from a full Node image, copies the workspace, runs a frozen install against the root lockfile, and then runs nx build api. It is the only stage that sees every workspace dependency and the build toolchain. If CI already runs the build, you can skip this stage and use dist/apps/api as the build context. The image then cannot pick up anything the build did not emit.

The runtime stage starts from a slim Node base. Order the instructions for layer caching:

  1. Copy only dist/apps/api/package.json and package-lock.json.
  2. Run npm ci --omit=dev, or pnpm install --frozen-lockfile --prod. With Yarn, use the frozen or immutable production install for your Yarn version.
  3. Copy the compiled main.js and assets.

The install layer is invalidated only when the pruned manifest or lockfile changes. A change to application code rebuilds only the final copy layer, so a typical commit does not trigger a dependency reinstall. The frozen flag makes the build fail if the pruned lockfile and package.json disagree, instead of silently resolving new versions.

Harden the final stage:

  • Set NODE_ENV=production.
  • Switch to the non-root node user that official Node images provide.
  • Leave out compilers and Python unless a native module needs to build at install time. If one does, compile it in an intermediate stage and copy the result across.

The .dockerignore keeps the context small and the cache stable. It should exclude:

  • node_modules
  • .nx and other local cache directories
  • .git
  • every app and library source tree the image does not build from

A stale local node_modules sent with the context will otherwise invalidate layers for no reason.

# syntax=docker/dockerfile:1
# Assumes the app's build target emits a pruned package.json and
# package-lock.json into dist/apps/api (e.g. generatePackageJson: true).

# ---- builder: full toolchain, whole workspace ----
FROM node:22-bookworm AS builder
WORKDIR /workspace
# Install from the root lockfile first so this layer survives code edits
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npx nx build api

# ---- runtime: slim base, production deps only ----
FROM node:22-bookworm-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app

# 1. Pruned manifest + lockfile only. BuildKit caches by file content,
#    so this layer is reused while the dependency set is unchanged.
COPY --from=builder /workspace/dist/apps/api/package.json /workspace/dist/apps/api/package-lock.json ./

# 2. Frozen production install: fails if lockfile and manifest disagree
RUN npm ci --omit=dev && npm cache clean --force

# 3. Compiled output last: a code change rebuilds only this layer
COPY --from=builder /workspace/dist/apps/api/ ./

# Files stay root-owned (read-only to the app). Run as the built-in
# non-root user from the official image.
USER node
EXPOSE 3000
CMD ["node", "main.js"]

# Matching .dockerignore (separate file):
#   node_modules
#   .nx
#   .git
#   apps/web
#   libs/ui

A two-stage Dockerfile builds the Nx api app with the full workspace, then installs only the pruned production dependencies in a slim, non-root runtime image before copying the compiled output, with the matching .dockerignore entries listed at the end.

How do you verify the generated package.json and measure image size?

Before trusting the build, open the package.json and lockfile that the build wrote to the output directory, not the ones at the workspace root. Check the following:

  • Dependency list. Every entry should trace to an import in the app or one of its libraries. Frontend frameworks, test runners or CLI tools in this list mean something pulled them in. Common causes are a shared library that re-exports too much, or a dependency declared in the wrong place.
  • Internal libraries. No @yourorg/* workspace package should appear as a dependency. If one does, the bundler treated a buildable or publishable library as external. The container's install step will then try to fetch it from a registry and fail, or install a stale published copy. Either configure the build to bundle that library, or publish it and pin it intentionally.
  • Lockfile. It should resolve only what the manifest lists. If your install step refuses it, the pruned lockfile no longer matches the manifest. Fix that mismatch rather than bypassing the lockfile check.

Next, run the container locally with production-like environment variables and exercise its startup paths: the health endpoint, database connection, migrations and any lazily required module. A missing runtime dependency often surfaces only when that code path runs.

Finally, compare images with docker image ls for total size and docker history to see which layer grew.

As an illustrative estimate, assume the root production dependencies include a frontend framework, a component library and two other services' SDKs, totalling a few hundred megabytes. If this API needs only an HTTP framework, an ORM and a logger, its pruned tree might be a few tens of megabytes. Measure your own images; don't rely on this example.

#!/usr/bin/env bash
# Verify the pruned build output for one app, then compare image sizes.
set -euo pipefail

OUT=dist/apps/api     # build output dir, not the workspace root
SCOPE='@yourorg/'     # internal workspace package scope

# 1. List every runtime dependency so each can be traced to an import.
jq -r '.dependencies // {} | keys[]' "$OUT/package.json"

# 2. Fail if an internal library leaked in as an external package.
if jq -r '.dependencies // {} | keys[]' "$OUT/package.json" | grep -F "$SCOPE"; then
  echo 'Internal library listed as a package: bundle it or publish and pin it.' >&2
  exit 1
fi

# 3. Build the image, then run it with production-like settings.
docker build -t api:pruned .
docker run -d --name api-check -p 3000:3000 \
  -e NODE_ENV=production \
  -e DATABASE_URL='postgres://app:placeholder@host.docker.internal:5432/app' \
  api:pruned

# Give the app time to boot, then hit the health endpoint.
sleep 5
curl -fsS
# Also exercise migrations, the DB connection and lazily required modules.
docker logs api-check
docker rm -f api-check

# 4. Compare total size against the previous image, then see which layer grew.
docker image ls api
docker history --format '{{.Size}}\t{{.CreatedBy}}' api:pruned

A shell checklist that lists the generated package.json dependencies, fails if an @yourorg/ workspace library appears as a package, smoke-tests the container's startup paths, and compares image and layer sizes with docker image ls and docker history.*

When should you avoid pruned lockfiles, and what breaks?

Pruning works from static analysis. Nx reads import and require statements to build the project graph, then copies only the matching entries from the root lockfile. Anything the analyzer cannot see is left out.

Dynamic loading

These cases are common sources of missed packages:

  • Computed require strings, such as require(\./adapters/${name}`)` or a package name assembled at runtime.
  • Plugin systems that discover modules by naming convention.
  • ORM or database drivers selected by configuration, where the code imports the ORM but the ORM loads the driver internally.
  • Packages referenced only in config files, such as a logger transport named in JSON.

The build succeeds and the image starts. The failure is a Cannot find module error at runtime, often on the first request that reaches that code path. To fix it, declare these packages explicitly in the app's dependencies. Then add a CI smoke test that starts the container and exercises those paths before the image is pushed.

Native modules

A lockfile resolved on a glibc machine can select prebuilt binaries that fail on Alpine (musl), and the reverse is also true. Keep the base image libc consistent with where you resolve dependencies, or rebuild native modules inside the image.

Package manager and version drift

Pruning support and fidelity vary across npm, Yarn classic, Yarn Berry and pnpm, and across Nx versions. Run a frozen install against the pruned lockfile in CI. If that install fails, the pruned lockfile is wrong.

Divergent versions

If one app needs a different version of a shared dependency, it conflicts with the single-version policy. Pruning cannot resolve that conflict.

Treat the pruned lockfile as a derived artifact. The committed root lockfile is the source of truth, and it should be installed frozen in CI.

What are the alternatives to generatePackageJson for Nx Docker images?

Four approaches are common, and each trades away something different.

Approach Image size Reproducibility Layer caching Native / file-system packages Self-contained Dockerfile Nx cache
Copy root lockfile Largest High Busts on any workspace dependency change Work Yes Unused
generatePackageJson + pruned lockfile Small High, if the root lockfile is consistent Busts only when this app's dependencies change Work No, needs a prior Nx build Used in CI
Single-file bundle, no node_modules Smallest High Rarely busts Often break No Used in CI
Full build inside Docker Depends on install strategy High Busts on most source changes Work Yes Unavailable unless remote cache is configured

Copying the root lockfile is simple and correct, but every service ships every workspace dependency. A full bundle avoids node_modules entirely. Bundlers, however, cannot inline compiled .node binaries. They also break packages that load assets through __dirname, such as templates, WASM files, or migration directories. Each of those needs an external or copy-asset exception.

Building inside Docker keeps the Dockerfile self-contained, so anyone can run docker build without the monorepo toolchain. The cost is losing Nx's computation cache, which is usually the largest speedup in CI.

generatePackageJson sits between these options. The build runs in CI with the cache, and the image installs only the dependencies the project graph says this app imports. Native modules still install normally. The cost is a two-step build, so the Dockerfile only works on a prepared dist directory.

How does this pattern affect CI cost and engineering time?

Order matters in CI. Run the Nx build first, then docker build. The Nx step is where computation caching and affected detection apply. If you put the Nx build inside the Dockerfile, it runs in an isolated build context with no Nx cache, so every image build repeats work Nx has already done.

An illustrative sequence looks like this:

  1. Run nx affected -t build with --base set to the last successful main commit and --head set to the current commit.
  2. List changed projects with nx show projects --affected, using the same base and head.
  3. For each listed project that is a deployable backend app, run docker build against its output directory.
  4. Tag that image with the app name and commit SHA, then push it.

Apps that were not affected keep their previous image tag, so nothing is rebuilt or pushed for them.

Here is how the time savings add up.

Illustrative estimate (assumed numbers, not a benchmark):

  • Runner minutes saved per day = (backend apps − affected apps per run) × minutes per image build and push × runs per day
  • Assumed inputs: 6 apps, 2 affected per run, 4 minutes per image, 30 runs per day
  • Result: (6 − 2) × 4 × 30 = 480 runner-minutes per day

Pruned images also save time in other ways:

  • Pulls on deploy and autoscaling are faster because the images are smaller.
  • Dependency layers stay cached until that app's dependencies change.
  • Scanners report fewer CVEs to triage, because unused packages are not in the image.

Weigh this against the upfront work. You need a smoke test that starts each container. You also need explicit handling for dynamically required modules, which the project graph cannot see. Budget for that before the savings show up.

#!/usr/bin/env bash
# Build affected apps with Nx, then build and push images only for affected backend apps.
set -euo pipefail

REGISTRY="registry.example.com/acme"   # placeholder registry
BASE_SHA="${BASE_SHA:?set to last successful main commit}"
HEAD_SHA="$(git rev-parse HEAD)"

# 1. Nx build runs on the CI runner, so computation caching and affected detection apply.
#    Each backend app's build is assumed to emit a pruned package.json and lockfile
#    into dist/apps/<app>.
npx nx affected -t build --base="$BASE_SHA" --head="$HEAD_SHA"

# 2. List affected application projects using the same base and head.
AFFECTED_APPS="$(npx nx show projects --affected --type app --base="$BASE_SHA" --head="$HEAD_SHA")"

# 3. Keep only deployable backend apps. Here that is any app with a Dockerfile.
for app in $AFFECTED_APPS; do
  if [[ ! -f "apps/$app/Dockerfile" ]]; then
    echo "skip $app (no Dockerfile)"
    continue
  fi

  image="$REGISTRY/$app:$HEAD_SHA"

  # 4. The build context is the Nx output directory, not the monorepo root.
  #    The image therefore sees only built code and the pruned lockfile.
  docker build -f "apps/$app/Dockerfile" -t "$image" "dist/apps/$app"
  docker push "$image"
  echo "pushed $image"
done

# Unaffected apps are not rebuilt. Deployments keep their previous image tags.

An illustrative CI script that runs the Nx affected build first. It then builds, tags by app name and commit SHA, and pushes images only for affected backend apps that have a Dockerfile, using each app's dist directory as the Docker build context.

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 pruned 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.