What is an Nx pruned lockfile build, and why does COPY . . fail in a monorepo?
A pruned lockfile build uses a small, app-specific folder as the Docker build context instead of the whole repository. When you build a Node app with Nx's generatePackageJson option enabled, Nx writes two extra files next to the compiled output in dist. The first is a package.json listing only the third-party packages that app imports. The second is a lockfile trimmed to match. You point docker build at that output folder, so the image only sees what the app needs to run.
The naive approach copies the full workspace and runs an install from the root package.json and lockfile. This works at first, but it causes three problems as the workspace grows:
- Every image gets every dependency. A small HTTP service ships with the ORM, queue client, and PDF library that belong to other apps. That makes the image larger and gives it more code to patch.
- The dependency layer rarely stays cached. Docker cache keys depend on file contents. When any team bumps any package, the root lockfile changes, and every service's install layer rebuilds, including services that never use that package.
- Auditing is harder. If a scanner flags a package inside an image, you have to work out whether the app actually loads it or whether it only came along with the root install.
This matters most to backend and platform engineers running several Node services from one Nx workspace. With pruned builds, you get fewer cache-busting rebuilds, shorter CI runs, and a dependency list per image that is short enough to review.
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
USER node
CMD ["node", "main.js"]
A Dockerfile that builds one Nx app from its pruned output folder, so the install layer contains and caches only that app's dependencies.
Who should use Nx pruned lockfile builds?
Pruned builds fit teams that deploy more than one Node application as a container from a single Nx workspace. The more the apps' dependency sets differ, the more you gain. Typical fits:
- Platform and DevOps engineers who own the CI pipeline and image registry, and who see every service rebuild its install layer whenever any team touches the root lockfile.
- Backend teams running several Node services (APIs, workers, schedulers) that share some workspace libraries but have different third-party dependencies, such as one service using a PDF library and another using a queue client.
- Teams with security or compliance review of images, who need each image's dependency list to reflect what the app actually loads so that scanner findings can be triaged per service.
It is a weaker fit in a few cases. If the workspace has one deployable app, the root lockfile already equals the app's lockfile, so pruning adds steps without reducing anything. If the apps rely heavily on runtime plugin loading, the static graph will miss packages and you will spend time declaring them by hand. If the team is already on pnpm and prefers to keep the original lockfile, the alternatives at the end of this article may suit better. Frontend apps served as static files from a web server image usually don't need a Node install in the image at all, so pruning does not apply to them.
How does a pruned lockfile build work end to end?
The flow has four stages. Each one produces the input for the next.
- Nx builds the project graph. It statically analyzes the app's source and the workspace libraries it imports, and records each third-party import as a dependency on an external
npm:node. - The build target compiles and prunes. With
generatePackageJson: true, the build writes the compiled JavaScript todist/apps/<app>, plus apackage.jsoncontaining only the external packages the graph traced to the app, with versions taken from the root manifest. It also writes a lockfile pruned from the root lockfile to those packages and their transitive dependencies. - Docker uses the output folder as its context.
docker buildreceives only that folder. The Dockerfile copies the manifest and lockfile first, runs a frozen production install, and then copies the compiled code. The install layer's cache key depends only on this app's manifest and lockfile. - CI verifies and ships the image. A smoke test starts the container to catch packages the static graph missed, and scanners read the pruned lockfile or the image instead of the root lockfile.
The sections below cover each stage in detail: how the graph is built, how to enable and inspect the pruned output, how to write the Dockerfile, and how to wire it into CI.
How does Nx decide which dependencies an app needs?
Nx does not scan node_modules or trust the root package.json. It builds the project graph by statically analyzing every source file in the app and the workspace libraries it imports, then records each resolvable package specifier as an edge to an external npm: node. When generatePackageJson runs, Nx collects those external nodes for the app, takes their versions from the root manifest, and prunes the root lockfile down to that set plus their transitive dependencies.
Static analysis is used because it is deterministic and cacheable. It also means anything resolved at runtime is invisible to Nx:
- Dynamic requires:
require(someVariable)or a computedimport()path. - Config-driven plugin loading: ORMs that load
pgormysql2from a connection string, logging libraries that resolve transports by name, and migration tools that discover drivers or migration files through configuration. - Peer dependencies: optional peers that the app itself never imports may not reach the pruned output.
These gaps do not appear at build time. The image builds cleanly and then fails at startup with Cannot find module.
You can fix this in two ways. You can add the missing packages to a package.json in the app's project root, which Nx uses as the base for the generated file. Alternatively, you can add an explicit side-effect import (for example, of the driver package) in the app's entry point so the graph records the edge.
app src + workspace libs ──static imports──┐
▼
project graph
(npm:* nodes for app)
│
┌───────────────────┼───────────────────┐
▼ ▼ ▼
dist/apps/api/ package.json pruned lockfile
main.js (app deps only) (app deps + transitive)
└───────────────────┼───────────────────┘
▼
docker build context
app src + workspace libs app project-root package.json
(static import / require) (explicit: pg, mysql2, transports)
│ │
▼ │
┌─────────────────────────┐ │
│ project graph │ │
│ app ──► npm:* nodes │ │
└────────────┬────────────┘ │
▼ ▼
┌───────────────────────────────────────────────────────┐
│ build with generatePackageJson │
│ - versions taken from root package.json │
│ - root lockfile pruned to set + transitive deps │
└───────┬────────────────────┬─────────────────────┬────┘
▼ ▼ ▼
┌──────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ bundle │ │ pruned │ │ pruned │
│ (main.js) │ │ package.json │ │ lockfile │
└──────┬───────┘ └────────┬─────────┘ └────────┬────────┘
└────────────────────┼──────────────────────┘
▼
┌──────────────────────────────┐
│ dist output = Docker build │
│ context: install, then run │
└──────────────────────────────┘
Invisible to the graph: require(var), computed import(),
config-loaded drivers/transports, unimported peer deps
Static imports form the project graph's npm: nodes, which combine with an app-level package.json to produce the bundle, pruned package.json and pruned lockfile used as the Docker build context.*
How do you enable generatePackageJson and inspect the pruned output?
Pruning is opt-in. In the app's build target, set generatePackageJson: true under options. Several bundling executors accept it, but support and exact naming have shifted across Nx releases, so confirm the option against the Nx docs for your installed version before relying on it. After nx build api, the output directory should contain the compiled entry point, a generated package.json listing only the third-party packages the project graph traced to the app, and a lockfile in your package manager's format, pruned to those packages and their transitive dependencies.
Inspect these artifacts before building an image on them. The pruning is only as good as the graph, and a wrong graph produces a container that fails at runtime.
- Diff the generated
package.jsonagainst the root one. Every entry should exist in the root manifest. Missing packages usually mean a dynamicrequireor a config-loaded plugin the graph couldn't see. - Compare versions against the root lockfile. The pruned lockfile should pin the exact versions the root lockfile resolved. If they differ, the image no longer runs what your tests exercised.
- Check how internal libraries are handled. Workspace libraries should be bundled into the output. If they appear as
workspace:protocol or relative path dependencies, the install will fail outside the repository, because those targets don't exist in the build context.
As an early gate, run a frozen install inside the output directory: npm ci, pnpm install --frozen-lockfile, or the equivalent for your Yarn version. If the manifest and lockfile disagree, this fails immediately, before Docker or CI is involved.
#!/usr/bin/env bash
set -euo pipefail
OUT=dist/apps/api
nx build api
ls -la "$OUT" # expect: main.js, package.json, package-lock.json
jq -r '.dependencies // {} | keys[]' "$OUT/package.json" | sort > /tmp/pruned.txt
jq -r '(.dependencies // {}) + (.devDependencies // {}) | keys[]' package.json | sort > /tmp/root.txt
echo "In pruned manifest but not root:"
comm -23 /tmp/pruned.txt /tmp/root.txt
while read -r dep; do
key="node_modules/$dep"
root_v=$(jq -r --arg k "$key" '.packages[$k].version // "missing"' package-lock.json)
out_v=$(jq -r --arg k "$key" '.packages[$k].version // "missing"' "$OUT/package-lock.json")
[ "$root_v" = "$out_v" ] || echo "MISMATCH $dep root=$root_v pruned=$out_v"
done < /tmp/pruned.txt
jq -r '.dependencies // {} | to_entries[]
| select(.value | test("^(workspace:|file:|link:|\\.)"))
| "BAD REF \(.key): \(.value)"' "$OUT/package.json"
(cd "$OUT" && npm ci --ignore-scripts)
A bash check that builds the app with generatePackageJson enabled, then diffs the pruned manifest against the root, compares locked versions, flags workspace or path references, and runs a frozen npm ci in the output directory.
Writing a multi-stage Dockerfile that uses dist as the build context
Point docker build at the app's output directory (for example dist/apps/api) rather than the workspace root. The daemon then receives only the compiled bundle, the generated package.json, and the pruned lockfile, so nothing from sibling apps can leak into the image or invalidate its cache.
Use at least two stages. In the first, copy only package.json and the lockfile, then run the frozen install for the same package manager that produced the lockfile: npm ci, pnpm install --frozen-lockfile, or your Yarn version's equivalent. Add the production-only option where it applies. Because this layer depends only on those two files, a source-only change reuses the cached node_modules. Only a dependency change triggers a reinstall. In the final stage, copy node_modules from the install stage, then copy the built JavaScript last.
Always run the install inside the same base image you ship. Native addons compile against the image's libc and CPU architecture. A node_modules built on a glibc x86 CI runner can fail at runtime on an Alpine (musl) or ARM image. Packages that distribute per-platform binaries as optional dependencies need extra care. Depending on the package manager, pruning may keep all platform variants or only the one matching the machine that ran the build. Before relying on the pruned lockfile, check that it contains an entry for your image's platform.
Add a short .dockerignore in the output directory as a guard. Exclude node_modules, .env*, and source maps if you don't ship them. That way a local test install or a stray secrets file never ends up in the context.
FROM node:20-alpine AS deps
WORKDIR /app
RUN apk add --no-cache python3 make g++
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
FROM node:20-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY . .
USER node
CMD ["node", "main.js"]
A two-stage Dockerfile built from dist/apps/api that installs from the pruned lockfile inside the Alpine image, so the dependency layer caches separately from the compiled code.
How do you wire Nx pruned builds into CI and verify the image?
The pipeline has three steps, run in this order. First, build the app with nx build api, or with nx affected -t build so only changed projects rebuild. Second, run docker build with dist/apps/api as the context. Third, start the container and run a smoke test before pushing. The test can be small: start the image, poll the health endpoint until it answers or a timeout expires, then stop it. A missing runtime dependency usually crashes the app at startup, so this catches most pruning mistakes cheaply.
Let the build produce the context. Don't maintain it by hand. A hand-curated context drifts as soon as someone adds an import, and nothing fails until production. When the context comes from the build, it always reflects the current dependency graph.
That only holds if Nx caching is configured correctly. The build target's outputs must cover the whole output directory, including the generated package.json and lockfile. Otherwise a cache hit can restore a partial dist. The inputs must include the root package.json and lockfile, so a dependency bump invalidates the cache instead of reusing an old pruned lockfile.
To verify the result:
- List the installed packages inside the final image with your package manager's list command, scoped to production dependencies. Look for anything the app shouldn't need.
- Point security scanning at the pruned lockfile in
dist, or at the built image, not at the root lockfile. Scanning the root lockfile reports vulnerabilities in packages the image doesn't contain. - On your own repo, compare image size and the dependency list against the previous whole-repo build. Keep both results as a baseline for future changes.
How can pruned builds save engineering time?
The savings come from three places: fewer dependency reinstalls in CI, less time triaging scanner findings, and fewer wasted rebuilds of services that a change never touched.
CI install time. With a root-context build, any change to the root lockfile invalidates the install layer of every service image. With pruned builds, only services whose pruned lockfile actually changed reinstall. Combined with nx affected -t build, services untouched by a commit are not rebuilt at all.
Illustrative estimate, not a measured result. Assumed inputs: 8 services in one workspace, 20 root lockfile changes per week, each change affecting the dependencies of 2 services on average, and a cold install layer taking 3 minutes per image.
- Root-context builds: 20 changes × 8 images × 3 minutes = 480 CI minutes per week spent reinstalling.
- Pruned builds: 20 changes × 2 images × 3 minutes = 120 CI minutes per week.
Under these assumed inputs, roughly three quarters of install time goes away. Your numbers depend on how often the lockfile changes, how many services share dependencies, and how slow your installs are, so measure on your own pipeline before and after.
Waiting time for engineers. CI minutes become engineer time when someone is waiting on a pipeline to merge or deploy. Shorter image builds shorten that wait on every pull request that touches dependencies.
Security triage. When each image's lockfile lists only what the app imports, a scanner finding against an image is relevant to that service. Engineers no longer spend time proving that a flagged package in a root-context image is never loaded by the app that carries it.
Debugging dependency conflicts. A per-app manifest shows at a glance which packages a service depends on, which narrows the search when an upgrade breaks one service.
These savings are offset by the costs described in the next section: declaring runtime-loaded modules by hand, verifying the regenerated lockfile, and the extra CI steps. For a workspace with one or two services that rarely change dependencies, the net saving can be close to zero.
When should you avoid Nx-generated pruned lockfiles?
Pruning swaps a large image for a second dependency graph that Nx computes from your code instead of one you wrote. In several situations that costs more than it saves.
Nx builds the graph from static imports. It cannot see modules loaded by name at runtime, such as plugins resolved from config files, require calls with computed strings, database drivers chosen by connection string, or logger transports. The generated package.json leaves them out, and the failure shows up only as "module not found" inside the container, often on a code path your tests never ran.
The pruned lockfile is regenerated, not copied. Nobody on your team reviewed it. Depending on the package manager, it can fail a frozen install or resolve a transitive dependency to a different version. How faithfully it matches the root lockfile varies between npm, Yarn classic, Yarn Berry and pnpm, and also across Nx versions and executors. An Nx upgrade can therefore change what ends up in the image even when your code hasn't changed.
Per-app images also duplicate shared dependencies. A node that pulls ten services stores ten copies of the same framework instead of one shared base layer.
Developers pay too. Each app has two package.json files to debug, CI gains extra steps, and security scanners must be configured to read the generated manifests.
| Risk | Symptom | Mitigation |
|---|---|---|
| Dynamic or config-loaded modules | "module not found" only at container runtime | Declare them explicitly; add a container smoke test |
| Regenerated lockfile | Frozen install fails or versions drift | Diff against root lockfile in CI |
| Package manager and Nx variance | Image contents change after an upgrade | Pin Nx; re-verify images on upgrade |
| Duplicated dependencies | Higher pull time and node disk use | Shared base image for common dependencies |
| Developer overhead | Confusing debugging, scanner gaps | Document the flow; point scanners at dist |
What are the alternatives to Nx pruned lockfiles for monorepo Docker builds?
Nx pruning is one of three common approaches. The other two keep the real lockfile intact.
Root-context builds with workspace features. With pnpm, a first stage copies only the lockfile and runs pnpm fetch, which fills the store from the lockfile alone. That layer stays cached until the lockfile changes. A later stage copies the source and uses a deploy-style step filtered to one workspace package, producing a self-contained directory for the runtime image. The lockfile is never regenerated, so what installs in the image is exactly what installed on a developer's machine. This wins when Nx-generated lockfiles fail to install cleanly, or when plugins are loaded dynamically and static analysis cannot see them.
Shared dependency base image. Here you build one image with the common dependencies installed and have each service extend it. If many services run on the same nodes, the base layers are pulled once and shared on disk. The cost is that every service carries dependencies it does not use, and bumping the base image means rebuilding everything downstream.
| Approach | Context size | Cache behaviour | Lockfile fidelity | Setup effort | Ongoing maintenance |
|---|---|---|---|---|---|
| Nx pruned lockfile | Smallest | Per-app, invalidated by pruned output | Regenerated, can drift | Low | Watch for prune bugs |
| pnpm fetch + deploy | Root, filtered by .dockerignore |
Lockfile-keyed layer shared across apps | Exact | Medium | Low |
| Shared base image | Small per app | Base layers shared on nodes | Exact at base | Medium | Base rebuild cadence |
How to choose. For a small workspace on npm or Yarn, use Nx pruning. If the team has standardised on pnpm, use fetch and deploy. Once the service count is large enough that pull time and node disk use start to matter, add a shared base image.
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 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.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
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.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- 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.