Why does copying the monorepo root into a Docker context break per-service images?
The naive Dockerfile for a monorepo service copies the repository root, runs a full install, and builds one app. It works, but it fights Docker's layer cache. The install layer is keyed on the root package.json and lockfile, and those files describe every app in the workspace. Under a single-version policy, a teammate adding a PDF library to the billing service changes the shared lockfile. That change invalidates the install layer for the auth, notifications and gateway images too, even though none of them import the library. Each of those images then ships the library, along with every other package the monorepo uses. The context also contains the source of every app, so any COPY . . step is invalidated by unrelated edits, and the image may carry code it never runs.
The target state is a context that holds exactly one service: its compiled output, a package.json listing only the packages that service imports, and a lockfile pruned to those packages and their transitive dependencies. Docker then sees an install layer that changes only when that service's own dependency graph changes.
Root context Dist context
------------ ------------
repo/ dist/apps/billing/
├─ apps/* (all sources) ├─ main.js
├─ libs/* ├─ package.json (generated)
├─ package.json (all deps) └─ lockfile (pruned)
└─ lockfile (all deps)
│ │
install everything install billing deps only
cache busts on any dep change cache busts on billing dep change
This pattern suits backend and platform teams running several Node services in an Nx monorepo with one root package.json.
ROOT CONTEXT (naive) DIST CONTEXT (pruned)
+--------------------------+ +--------------------------+
| repo/ | | nx build billing |
| apps/* (all sources) | | + generated package.json |
| libs/* | | + pruned lockfile |
| package.json (all deps) | +------------+-------------+
| lockfile (all deps) | |
+------------+-------------+ v
| +--------------------------+
v | dist/apps/billing/ |
+--------------------------+ | main.js |
| docker build . | | package.json (billing) |
| COPY package.json, lock | | lockfile (pruned) |
| RUN install (all deps) | +------------+-------------+
| COPY . . | |
| RUN nx build billing | v
+------------+-------------+ +--------------------------+
| | docker build dist/... |
v | COPY package.json, lock |
+--------------------------+ | RUN install (billing) |
| image: billing | | COPY main.js |
| every package in repo | +------------+-------------+
| every app's source | |
+--------------------------+ v
cache key: root lockfile +--------------------------+
busts on ANY dep change | image: billing |
| billing deps only |
+--------------------------+
cache key: pruned lockfile
busts on billing dep change
The root-context build installs and ships every workspace dependency and invalidates its install layer on any lockfile change, while the dist-context build installs only the dependencies in billing's pruned lockfile.
Who should use this pattern?
Use it if most of the following are true:
- You deploy several Node services from one Nx workspace. With one or two services, the shared lockfile rarely invalidates anything you care about, and a root-context build is simpler.
- The workspace follows a single-version policy. All projects share one root
package.json, so a version copied from the root is correct for every service. - Services are bundled or compiled by an Nx executor that supports
generatePackageJson, such as the webpack, esbuild or tsc-based Node executors. - Several teams commit to the same repository. The benefit comes from isolating one team's dependency changes from other teams' images and caches.
- Image size, scan noise or CI time are real costs for you. Smaller per-service images mean fewer packages to scan and less data to push and pull.
It is a weaker fit for services that load modules dynamically, depend heavily on native modules with unusual build steps, or need dependency versions that diverge from the rest of the workspace. Those cases are covered in the section on when to avoid this approach.
How does it work?
The pattern has four stages, and each one narrows what the next stage sees:
- Nx builds the project graph. It parses every project's imports and records which workspace libraries and npm packages each service reaches, directly or through shared libraries.
- The build target emits a self-contained output folder. With
generatePackageJsonenabled,nx build <service>writes the compiled code, apackage.jsonlisting only the npm packages that service reaches in the graph, and a lockfile pruned from the root lockfile to those packages and their transitive dependencies. - Docker builds from that folder, not the repository root. A multi-stage Dockerfile copies the manifest and pruned lockfile, runs a frozen production install in its own layer, then copies the compiled code into a clean runtime image. The install layer's cache key is now the service's own dependency set.
- CI builds only affected services.
nx affected -t docker-buildmaps changed files onto the project graph and runs the image target only for services whose code or dependencies changed.
The following sections cover each stage in that order.
How does Nx work out which dependencies a service actually uses?
Nx builds a project graph before it runs any target. It parses the source files of every project, follows import and require statements, and records two kinds of edges: from a project to other workspace projects, and from a project to external npm packages. When the billing service imports a shared data-access library, and that library imports pg, the graph has a path from billing to pg even though billing's own code never mentions it. Pruning walks this graph from the service outward, so the dependency set covers the app and every library it reaches, not only the app's own files.
Versions come from the root package.json, and the lockfile supplies the resolved tree. This depends on the single-version policy. If every project shares one version of each package, Nx can copy the version from the root without guessing. If two services needed different versions of the same package, one root manifest could not describe both, and the pruned output would be wrong for one of them.
How an internal library is consumed decides whether it appears in the generated manifest:
| Library strategy | Generated package.json |
Build output | Caching |
|---|---|---|---|
| Bundled (default for most app builds) | Not listed; its npm imports are merged in | Inlined into the service bundle | Recompiled inside the app build; any lib change invalidates the app's cache entry |
| Buildable or publishable, treated as external | Can appear as a dependency alongside npm packages | Built separately to its own output folder | Has its own cached build target that can be reused across services |
If a library is treated as external, the image needs a way to install or copy that library, because it will not be inside the service bundle.
How do you enable generatePackageJson and produce a pruned lockfile?
For a Node application, the switch lives in the build target. In apps/orders-api/project.json, find the build target and add "generatePackageJson": true to its options object. The webpack, esbuild and tsc-based Nx executors accept this option. Check that the executor your project uses does too, because an unsupported option may be ignored without an error.
With the flag on, nx build orders-api writes more than compiled JavaScript. A typical dist/apps/orders-api folder then contains:
main.jsand any emitted assetspackage.jsongenerated from the project graph- a lockfile in the workspace's format, such as
package-lock.json,pnpm-lock.yamloryarn.lock
The generated package.json is deliberately sparse. It has a name (usually the project name), sometimes a version, and a dependencies map that lists only the npm packages this service imports, for example express and pg. It does not include react, the test runners or the build tools that sit in the root manifest. Version ranges are copied from the workspace, so the service declares what the monorepo already uses.
The lockfile is the part that makes this reproducible. Nx prunes the root lockfile down to the packages and transitive dependencies of that manifest and writes the result next to it. Inside the image, npm ci, pnpm install --frozen-lockfile or yarn install --immutable then installs the same resolved versions you tested against in the monorepo, instead of re-resolving ranges at build time.
Lockfile pruning support has changed across Nx releases and differs by package manager and lockfile version, especially for pnpm and Yarn Berry. Before you rely on it in CI, build one service and confirm that the emitted lockfile exists and that the frozen install succeeds.
{
"name": "orders-api",
"targets": {
"build": {
"executor": "@nx/webpack:webpack",
"options": {
"target": "node",
"outputPath": "dist/apps/orders-api",
"main": "apps/orders-api/src/main.ts",
"tsConfig": "apps/orders-api/tsconfig.app.json",
"generatePackageJson": true
}
}
}
}
dist/apps/orders-api/
├── main.js # compiled service entry point
├── package.json # generated from the project graph
└── package-lock.json # pruned lockfile (pnpm-lock.yaml / yarn.lock in those workspaces)
{
"name": "orders-api",
"version": "0.0.1",
"dependencies": {
"express": "^4.19.2",
"pg": "^8.11.3"
}
}
cd dist/apps/orders-api && npm ci --omit=dev
This example enables generatePackageJson on an Nx Node build target, then shows the resulting dist layout with its pruned lockfile, a sample minimal package.json, and a frozen-install check. Version ranges are placeholders.
Writing a multi-stage Dockerfile that uses dist as the docker context
Once you have that output, the build no longer needs the workspace. Pass dist/apps/<service> as the build context and point at the Dockerfile with -f, for example docker build -f apps/orders/Dockerfile dist/apps/orders. The daemon then receives only the compiled bundle, the generated package.json and the pruned lockfile. If your tooling requires the repository root as the context, add a .dockerignore that excludes everything with * and then re-includes only that service's dist directory.
The Dockerfile has two stages. The first stage copies only package.json and the lockfile, then runs a frozen production install: npm ci --omit=dev, pnpm install --frozen-lockfile --prod, or yarn install --immutable with production-only settings for Yarn Berry. A frozen install fails if the lockfile and manifest disagree. That failure is the behaviour you want, because it catches a broken prune before the image ships. The second stage starts from a clean runtime image. It copies node_modules from the first stage, then copies the compiled code, sets NODE_ENV=production, and switches to a non-root user. The official Node images ship a node user you can reference with USER node.
The order of these steps controls caching. Docker reuses a layer only when that layer's inputs and every layer before it are unchanged. Because the dependency install comes before the source copy, a code-only commit leaves package.json and the lockfile byte-identical, so Docker reuses the install layer and rebuilds only the final copy.
Native modules compile or download prebuilt binaries for the platform where they are installed. Run the install stage on the same libc and CPU architecture as the runtime stage. A node_modules built on glibc will fail on an Alpine (musl) image, and one built for amd64 will fail on arm64.
FROM node:20-bookworm-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
FROM node:20-bookworm-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
COPY --chown=node:node package.json ./
COPY --chown=node:node . ./
USER node
EXPOSE 3000
CMD ["node", "main.js"]
A two-stage Dockerfile that uses dist/apps/orders as its build context. It runs a frozen production install from the pruned lockfile in its own cached layer, then copies the compiled code into a glibc runtime image that matches the install stage and runs as the non-root node user.
How do you wire docker-build into nx affected in CI?
Give each deployable service its own docker-build target with dependsOn set to build. Nx then runs the service's build first and puts the pruned package.json and lockfile in dist before Docker reads that directory as its context. The target can be a nx:run-commands call to docker build that points at the service's output path. Because the image depends on the build output, the target belongs to the project and moves through the project graph with it.
In CI, run nx affected -t docker-build. Nx compares the files changed between a base and head commit, maps them onto the project graph, and runs the target only for affected services. A change to a shared library rebuilds every service that imports it. A change confined to one service rebuilds that image alone. Tag each image with the full commit SHA, not a moving tag like latest, so a deployment points at an exact build.
The base SHA determines what counts as changed:
- Pull requests: use the merge-base with the target branch.
- Main: use the last commit whose pipeline succeeded, not
HEAD~1. If a pipeline fails and the next one diffs only against its parent, the services changed in the failed run are never rebuilt. - Fetch history: shallow clones often lack the base commit. Nx then errors or treats everything as affected, and you are back to rebuilding every image.
When the base is set correctly, a team's commit triggers builds only for the services in its dependency graph. Pipelines stay short, registries hold fewer duplicate images, and other teams' layer caches stay intact.
name: ci
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
actions: read # nx-set-shas queries past workflow runs to find the last green commit on main
jobs:
images:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history, so the base commit exists locally (a shallow clone breaks the diff)
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
# Exports NX_BASE and NX_HEAD.
# PRs: base = merge-base with main.
# main: base = last commit whose workflow succeeded, not HEAD~1, so a failed run's changes are retried.
- uses: nrwl/nx-set-shas@v4
with:
main-branch-name: main
- name: Build images for affected services only
env:
# Immutable tag. On PRs, use the PR head commit rather than the synthetic merge commit.
IMAGE_TAG: ${{ github.event.pull_request.head.sha || github.sha }}
# Each service's docker-build target (dependsOn: ["build"]) runs something like:
# docker build -t registry.example.com/{projectName}:$IMAGE_TAG dist/apps/{projectName}
run: npx nx affected -t docker-build --base=$NX_BASE --head=$NX_HEAD
A GitHub Actions job that fetches full history, sets the Nx base SHA (merge-base on PRs, last successful commit on main), and runs nx affected -t docker-build so only services whose project graph changed get images, each tagged with its commit SHA.
How do you verify the generated package.json, the lockfile and layer reuse?
Run these checks once when you first set up the pipeline, and again whenever you change the build configuration or upgrade Nx.
1. Inspect the generated package.json
Build the service with nx build api, then open dist/apps/api/package.json. List its dependencies with jq '.dependencies' dist/apps/api/package.json and compare them with the imports you expect. Look for two kinds of mistakes:
- Packages that should not be there. Frontend libraries or test tooling suggest that a shared library is pulling in more than it should.
- Packages that are missing. Anything loaded dynamically, through a string-based
require, or by a plugin system does not appear in the project graph, so Nx cannot detect it.
2. Validate the pruned lockfile
Copy the dist folder to a scratch directory and run npm ci there (or the equivalent for your package manager). npm ci fails when the lockfile and package.json disagree. That failure is the signal you want: catch the mismatch locally instead of inside a Docker build.
3. Run the image, not just the build
A successful build does not prove that the service starts. Run docker run --rm -p 3000:3000 api:local and call a health endpoint. Missing runtime dependencies only surface when the code that loads them executes.
4. Check size and layers
Run docker image ls api to see the total image size. Then run docker history api:local to see how much each layer contributes. The dependency install layer should be the largest. If it is far larger than the dependency list suggests, the docker context is probably still including files it should not.
5. Confirm cache reuse
Make a change to source code only, rebuild, and run docker build --progress=plain. The install step should be reported as CACHED. If it reruns, the package.json or lockfile changed between builds, or a COPY of the source code happens before the install step. Diff the two generated package.json files to find which one it is.
How can it save engineering time?
The savings come from three places: fewer image builds, cheaper builds when they do run, and less follow-up work on the images you ship.
- Fewer builds per commit.
nx affectedskips services whose project graph did not change, so a commit to one service no longer rebuilds, pushes and redeploys every image in the workspace. - Cheaper rebuilds. With the install layer keyed on the pruned lockfile, a code-only commit reuses the cached dependency layer and only re-copies the compiled output. A dependency change in one service no longer busts the install cache for the others.
- Shorter feedback loops. Pull request pipelines finish sooner when they build one or two images instead of all of them, so engineers wait less before review and merge.
- Less triage. Each image contains only the packages its service imports. Vulnerability scanners report fewer findings for packages a service never loads, so teams spend less time deciding whether a reported issue applies to them.
- Earlier failure on bad dependency state. The frozen install in the Dockerfile fails the build when the manifest and lockfile disagree, instead of producing an image with re-resolved versions that only misbehaves after deployment.
An illustrative estimate shows how the first two effects combine. The inputs are assumed, not measured: a workspace with 10 services, a root-context image build that takes an assumed 4 minutes per service, and a pruned build that takes an assumed 1 minute when the install layer is cached. Consider a code-only commit to one service:
- Root context, every image rebuilt: 10 × 4 = 40 minutes of runner time.
- Root context with
nx affected, one image rebuilt: 1 × 4 = 4 minutes. - Pruned context with
nx affectedand a cached install layer: 1 × 1 = 1 minute.
Over an assumed 20 such commits per day, that is 800, 80 and 20 runner-minutes respectively. Your numbers depend on install size, runner cache persistence, registry speed and how often commits touch shared libraries. A change to a widely imported library still rebuilds every service that depends on it. Measure your own pipeline before and after the change rather than relying on these figures.
When should you avoid this approach, and what are the alternatives?
Pruning relies on static analysis, so it only sees imports it can resolve at build time. String-built require calls, plugin loaders, ORM database drivers and optional native dependencies are invisible to it. They fail with a module-not-found error when the container starts, not during the build, so CI stays green while the deployment breaks. You can list them explicitly in project configuration, but that list is maintained by hand and drifts as dependencies change.
Lockfile pruning has its own edge cases. Patched packages, overrides or resolutions, workspace: protocol references and peer dependencies can be dropped or rewritten, so a pruned install may resolve different versions than the root install. Using dist as the Docker context also ties every image build to the Nx toolchain. And because the pattern assumes a single root version of each dependency, it does not suit services that need divergent versions.
The operational cost grows with each service. Every image adds registry storage, another vulnerability scan to triage, and another target for automated base-image rebuilds.
| Approach | Image size | Cache behaviour | Native module support | Debuggability |
|---|---|---|---|---|
| Root context, full install | Largest | Any root lockfile change invalidates the install layer | Good; modules are built on the target platform | Easy; familiar layout |
| Full bundle including node_modules | Smallest | Bundle rebuilds on any code change | Poor; .node binaries need separate handling |
Harder; needs source maps |
| Package-manager pruning or deploy commands | Small | Stable when the lockfile is stable | Good | Easy; standard node_modules |
| Single shared image | Large, but only one image | One shared cache; any change rebuilds it for all services | Good | Simple; one image to inspect |
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.
- 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.