Why does building Nx apps from the monorepo root hurt Docker builds?
If your Nx workspace ships several Node services, the default Dockerfile usually copies the repository root, runs a full install, and builds one app. That setup has three costs that grow with the workspace.
The context is the whole repo. docker build . sends every tracked file the .dockerignore doesn't exclude to the builder: other apps, libraries, docs, and test fixtures. Context transfer gets slower, and an unrelated file change can invalidate any COPY that touches it.
One lockfile change rebuilds every image's dependencies. The install layer is keyed on the root lockfile. Bumping a dev dependency for a frontend changes that file, so the cached npm ci (or equivalent) layer of every backend image is invalidated. Each service then reinstalls everything, even though its own dependencies didn't change.
Images carry packages the service never imports. A root install pulls in the dependency union of every project. The runtime image ends up larger and has a wider vulnerability surface. Scanners flag CVEs in libraries the service never loads.
The fix is to treat each app's build output as a self-contained deployable: the bundled code, a generated package.json listing only what the bundle imports, and a lockfile pruned to match. Point Docker at that dist folder instead of the root.
Root context dist context
------------ ------------
repo/ ──► docker dist/apps/orders/
├ apps/* (all) build ├ main.js
├ libs/* (all) ├ package.json (orders deps only)
├ package.json └ lockfile (pruned)
└ lockfile (all) │
│ ▼
install: every dep install: orders deps
cache key: root lock cache key: pruned lock
ROOT CONTEXT: one build context for every image
+------------------------------+
| repo/ |
| apps/* libs/* docs/ |
| package.json (all projects) |
| lockfile (all projects) |
+---------------+--------------+
| docker build . (whole repo sent)
+---------+---------+
v v v
+---------+ +---------+ +---------+
| orders | | billing | | web |
+---------+ +---------+ +---------+
install: union of all deps cache key: root lockfile
any root lockfile change ---> every install layer rebuilt
DIST CONTEXT: one build context per app (nx build output)
+------------------------+ +------------------------+
| dist/apps/orders/ | | dist/apps/billing/ |
| main.js (bundle) | | main.js (bundle) |
| package.json (orders) | | package.json (billing) |
| lockfile (pruned) | | lockfile (pruned) |
+-----------+------------+ +-----------+------------+
| docker build | docker build
v v
[ orders image ] [ billing image ]
install: orders deps only install: billing deps only
key: orders pruned lockfile key: billing pruned lockfile
frontend-only dep bump ---> pruned lockfiles unchanged ---> cache hit
Building from the repo root sends the whole workspace and keys every service's install layer on one shared lockfile; building from each app's dist folder ships only its bundle, generated package.json and pruned lockfile, so unrelated dependency changes leave its install layer cached.
How does generatePackageJson produce a pruned lockfile?
When generatePackageJson is set to true on an Nx build target, the executor uses the project graph to work out which npm packages the app actually needs. The graph records an edge for each static import or require it can resolve, so the result is the app's own external dependencies plus those of any workspace libraries it imports. Nx writes a package.json with only those entries into the output directory. It also writes a lockfile alongside it, using your package manager's format and pruned from the root lockfile. The pinned versions therefore match what you tested against in the monorepo.
Why a runtime install is still needed
With @nx/webpack:webpack targeting Node, packages from node_modules are usually left external instead of being bundled into main.js. This avoids problems with native addons, packages that read their own files at runtime, and very large bundles. Your bundle still calls require('express'), so the image needs a node_modules folder. The pruned manifest and lockfile let you install exactly that set and nothing else. The esbuild executor can follow the same pattern when third-party packages are kept external.
Internal workspace libraries work differently. Code under libs/ is compiled into the bundle, so those libraries never show up as installable dependencies.
Expected output
The build target in apps/orders/project.json uses the webpack executor with target: "node", an outputPath of dist/apps/orders, and generatePackageJson: true. After running the build, expect:
dist/apps/orders/main.jsdist/apps/orders/package.jsondist/apps/orders/package-lock.json(oryarn.lock/pnpm-lock.yaml)
Option names, defaults, and emitted filenames have changed between Nx releases. Check them against the Nx docs for the version you have installed.
{
"name": "orders",
"projectType": "application",
"sourceRoot": "apps/orders/src",
"targets": {
"build": {
"executor": "@nx/webpack:webpack",
"outputs": ["{options.outputPath}"],
"options": {
"target": "node",
"compiler": "tsc",
"main": "apps/orders/src/main.ts",
"tsConfig": "apps/orders/tsconfig.app.json",
"outputPath": "dist/apps/orders",
"generatePackageJson": true
}
}
}
}
A minimal apps/orders/project.json build target using the Nx webpack executor for Node with generatePackageJson enabled; verify option names against the Nx docs for your installed version.
How do you verify the generated package.json and lockfile before trusting them?
Treat the emitted files as build artifacts that need a test before any image is built from them.
Inspect and diff
Open dist/apps/orders/package.json and read the dependencies list. Each entry should be a package the app imports at runtime. Check for two failure modes: dev tooling that leaked in, and expected runtime packages that are missing. Then compare resolved versions in the pruned lockfile against the root lockfile for the same packages. They should match exactly. If they don't, the pruner re-resolved a range instead of copying the pinned entry, and the image will run code your tests never exercised.
Prove the lockfile is self-consistent
Run a clean install from an empty node_modules inside the output directory. Use npm ci for npm, pnpm install --frozen-lockfile for pnpm, or yarn install --immutable for Yarn Berry (--frozen-lockfile on Yarn classic). Frozen mode fails when package.json and the lockfile disagree, which is exactly the error you want CI to catch before the Docker build does.
Cover what the graph can't see
Nx's dependency graph comes from static imports. It misses:
- modules loaded with computed
require()paths - plugins named in config files, such as ORM drivers or logger transports
- peer dependencies the host package expects you to provide
Declare these in the project's own package.json, or use the build option your Nx version provides for this. Leave a comment explaining why each one is listed.
The final check is a boot smoke test in CI. Start the built container and wait for a health endpoint to respond. Fail the job on a non-zero exit or on a Cannot find module error in the logs. This catches omissions that a successful install cannot reveal.
#!/usr/bin/env bash
# Verify the pruned package.json and lockfile before building an image (npm, lockfile v2/v3).
set -euo pipefail
OUT=dist/apps/orders
# 1. Inspect: list emitted runtime deps; review for leaked dev tooling or missing packages.
jq -r '.dependencies | keys[]' "$OUT/package.json"
# 2. Diff: every pinned version in the pruned lockfile must equal the root lockfile entry.
# Nested node_modules paths can hoist differently; a MISSING result there needs a manual look.
jq -r '.packages | to_entries[] | select(.key != "" and .value.version != null) | "\(.key) \(.value.version)"' "$OUT/package-lock.json" |
while read -r path version; do
root=$(jq -r --arg p "$path" '.packages[$p].version // "MISSING"' package-lock.json)
[ "$root" = "$version" ] || { echo "MISMATCH $path pruned=$version root=$root"; exit 1; }
done
# 3. Self-consistency: frozen install from an empty node_modules in a scratch copy.
# npm ci fails if package.json and package-lock.json disagree.
TMP=$(mktemp -d)
cp -r "$OUT"/. "$TMP"
(cd "$TMP" && rm -rf node_modules && npm ci)
# 4. Boot smoke test: catches dynamic requires, config-loaded plugins and missing peers.
docker build -t orders:verify -f apps/orders/Dockerfile .
docker run -d --name orders-smoke -p 3000:3000 orders:verify
trap 'docker rm -f orders-smoke >/dev/null 2>&1' EXIT
ok=0
for _ in $(seq 1 30); do
if curl -fsS >/dev/null; then ok=1; break; fi
# Stop waiting if the container already crashed on startup.
[ "$(docker inspect -f '{{.State.Running}}' orders-smoke)" = "true" ] || break
sleep 1
done
if docker logs orders-smoke 2>&1 | grep -q 'Cannot find module'; then
echo 'Missing runtime dependency'; docker logs orders-smoke; exit 1
fi
[ "$ok" = 1 ] || { echo 'Health check failed'; docker logs orders-smoke; exit 1; }
echo 'Pruned lockfile and image verified'
A CI script that lists the emitted dependencies, diffs pinned versions against the root lockfile, runs npm ci in a scratch copy of the output directory, and boot-tests the container to catch modules the static graph missed.
How do you write a multi-stage Dockerfile with dist as the docker context?
With the generated manifest verified, the Dockerfile can treat dist/apps/api as its entire world. The build context then holds only the bundle, package.json, and the pruned lockfile. Docker never uploads the monorepo, and nothing outside the app can invalidate a layer.
Stage layout
Use two stages built from the same slim Node base, such as the official node image's -slim variant.
- Deps stage. Copy only
package.jsonand the lockfile, then run the frozen production install (npm ci --omit=dev, or your package manager's equivalent) as a dedicated layer. Docker keys this layer's cache on those two files alone. A change to application code leaves the install cached. Only a dependency change for this specific app forces a reinstall. - Runtime stage. Copy
node_modulesfrom the deps stage, then copy the bundle last. Bundle changes are the most frequent, so this layer belongs at the end.
Switch to the unprivileged node user that the official images ship, and set NODE_ENV=production.
Native addons
Packages such as bcrypt or sharp compile or download binaries for a specific OS, libc, and CPU architecture. A node_modules built on a macOS laptop or an Alpine CI runner will fail inside a Debian-based slim image. Install inside the deps stage so binaries match the target. If compilation needs python3, make, and g++, add them to the deps stage only, so the toolchain stays out of the runtime image.
Building
Point the context at the dist folder and pass the Dockerfile explicitly:
docker build -f apps/api/Dockerfile -t api:local dist/apps/api
The Dockerfile can stay in source control next to the app, while the context remains the pruned output.
# Build context is dist/apps/api (bundle + package.json + pruned lockfile).
# Build from the repo root:
# docker build -f apps/api/Dockerfile -t api:local dist/apps/api
ARG NODE_IMAGE=node:22-bookworm-slim
# ---- deps: install production dependencies inside the target OS/libc/arch ----
FROM ${NODE_IMAGE} AS deps
WORKDIR /app
# Native addons that compile from source need a toolchain. Keep it in this stage only.
RUN apt-get update \
&& apt-get install -y --no-install-recommends python3 make g++ \
&& rm -rf /var/lib/apt/lists/*
# Copy only the manifest and lockfile so this layer's cache depends on them alone.
COPY package.json package-lock.json ./
# Frozen production install. Native binaries are built or fetched for this image,
# never copied from the host.
RUN npm ci --omit=dev
# ---- runtime: slim base, production deps, non-root ----
FROM ${NODE_IMAGE} AS runtime
ENV NODE_ENV=production
WORKDIR /app
# Reuse the installed dependencies without bringing over the build toolchain.
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
# Bundle changes most often, so it is copied last.
COPY --chown=node:node . .
# The official node images ship an unprivileged 'node' user.
USER node
CMD ["node", "main.js"]
A two-stage Dockerfile that uses dist/apps/api as its build context. It installs production dependencies from the pruned lockfile in their own cached layer, compiles native addons inside the image, and runs the bundle as the non-root node user on a slim base.
Should the Nx build run in CI or inside a Docker builder stage?
That layout assumes nx build has already run on the CI runner. The alternative is to run it inside a builder stage of the Dockerfile. Each choice trades something away.
Building in CI first keeps the context to a few megabytes of bundle, package.json, and pruned lockfile. It also reuses whatever Nx cache the pipeline already has, whether local or remote, so an unchanged app costs almost nothing. The downside is that the bundle inherits the runner's environment. If the CI image runs a different Node major, libc, or CPU architecture than the runtime image, JavaScript usually survives, but native addons compiled during npm ci on the runner do not. Install production dependencies inside the image, never copy them from the runner.
Building in a builder stage is hermetic. The toolchain is pinned by the base image tag. The cost is that the context must be the repo root, and the Nx cache starts empty on every build unless you mount it with a BuildKit cache mount or give the stage remote-cache credentials. Keep the root context lean with a .dockerignore that excludes:
node_modulesdist- the local Nx cache directory (
.nx) .git- editor and coverage folders
| Concern | Build in CI, dist context |
Build in builder stage, root context |
|---|---|---|
| Context size | Small: one app's output | Large: whole workspace minus ignores |
| Reproducibility | Depends on runner setup | Pinned by base image |
| Nx cache reuse | Automatic | Only with mounted or remote cache |
| Native module risk | High if runner and image differ | Low |
| Build speed | Fast on cache hits | Slower, full install per build |
How do you wire docker-build into Nx targets and affected CI runs?
Define docker-build as its own target in each deployable project, using the nx:run-commands executor to call docker build against that project's dist folder, and set dependsOn to ["build"]. This gives you three things for free. Nx always produces fresh dist output before the image build starts. Affected detection covers images as well as compiled code. And a library change reaches only the containers that actually import it.
In CI, run nx affected -t docker-build. Projects whose source and dependency graph are unchanged are skipped entirely, so no image is built for them and nothing is pushed.
Tag each image with the project name and the commit SHA, for example registry/orders-api:<sha>. A deployment then pins an exact artifact, and rollbacks are a tag change. You can also hash the generated lockfile in dist and pass it as a build arg or a registry cache tag. Two commits with identical pruned dependencies then reuse the same install layer, even across branches.
Illustrative estimate (assumed inputs, not measured):
- 12 services
- 10 dependency bumps per week, each touching packages used by 2 services on average
- 90 seconds of dependency install per image
With a root lockfile, every bump invalidates the install layer in all 12 images: 10 × 12 × 90 s = 180 minutes per week.
With pruned lockfiles, only the 2 affected images reinstall: 10 × 2 × 90 s = 30 minutes.
That is 150 build-minutes saved per week. Engineers also wait less on each pipeline, which matters more than the minutes themselves.
When should you avoid per-project pruned lockfiles, and what are the alternatives?
Those savings assume the pruned install succeeds, and it does not always. Pruning support differs across package managers and lockfile formats, so test with the exact manager and lockfile version you ship. Workspace protocols, overrides or resolutions, patched packages, and aliased dependencies commonly break a frozen install against a generated lockfile. Dependencies loaded only at runtime, such as dynamic requires or optional drivers, never appear in the project graph. They fail at container startup, not at build time, and the smoke test that catches them adds pipeline time.
The operational cost also grows. Every project image adds tags and vulnerability scans, and a shared dependency upgrade still rebuilds every affected image. Internal libraries that nx webpack bundles into the app cannot be patched separately inside an image, so any fix means rebuilding the app. Generated output can drift across Nx upgrades. Pin the Nx version and re-verify the generated package.json and lockfile after every upgrade.
| Approach | Cache granularity | Image size | Reliability | Maintenance cost | Suits |
|---|---|---|---|---|---|
| Root lockfile, full install | Coarse: any lockfile change invalidates | Large | High | Low | Small teams, few apps |
| Root context, builder stage | Coarse, but layers are reusable | Medium | High | Medium | Teams that want builds out of CI runners |
| Bundle all dependencies | Per app | Small | Breaks on native modules | Medium | Pure-JS services |
| One shared base image | Shared dependency layer | Medium | High | Low per app | Many apps on a common stack |
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
.envby 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.