Why does the naive monorepo Docker build produce bloated images?

The usual first attempt at containerizing an Nx workspace looks reasonable. The Dockerfile copies the root package.json and lockfile, runs npm ci (or the pnpm or Yarn equivalent), copies the rest of the repository, builds one project, and starts it. Every service gets a near-identical Dockerfile with only the build target changed. This works, but it causes three problems.

Every service inherits every dependency. The root package.json describes the whole workspace. A small HTTP API ends up shipping the ORM, queue client, PDF renderer and image-processing libraries that other services use. It also ships the frontend toolchain, test runners and linters, unless you prune dev dependencies. Those packages add size, lengthen pull times on every node that schedules the container, and widen the surface that vulnerability scanners flag. Some of those findings will be in code the service never loads.

One lockfile change invalidates every image. Docker caches the install layer based on the files copied before it. With a single root lockfile, bumping a dependency used by one service changes that file for all of them. Every service then re-runs a full install on its next build, even services whose actual dependency set did not change.

Build contexts get large. Copying the repository root sends every app, library, fixture and asset to the builder unless .dockerignore is maintained carefully. That is slow on remote builders, and unrelated file changes can bust cached layers.

The goal for the rest of this tutorial is one image per service, built from a context and lockfile that hold only what that service needs.

# Naive per-service Dockerfile for an Nx workspace (the anti-pattern).
# Each service has a near-identical copy; only the project name changes.
FROM node:20-bookworm-slim

WORKDIR /workspace

# 1. Root manifest + root lockfile describe the WHOLE workspace.
#    Any change to package-lock.json (even for another service's dependency)
#    invalidates this layer and everything after it, for every service.
COPY package.json package-lock.json ./

# 2. Installs every dependency of every app and lib, including dev tooling
#    (test runners, linters, frontend bundlers) needed only to build.
RUN npm ci

# 3. Copies the entire repository: all apps, libs, fixtures and assets.
#    Unrelated edits elsewhere in the repo bust this layer's cache, and the
#    build context sent to the builder is as large as the repo allows.
COPY . .

# 4. Build just one project, but the image keeps everything above.
RUN npx nx build api

# 5. Runtime image = full workspace node_modules + full source tree + build output.
#    The output path depends on the project's build configuration.
CMD ["node", "dist/apps/api/main.js"]

A typical naive Nx service Dockerfile, annotated to show where every service inherits the full workspace dependency set, where a single root lockfile change invalidates the install layer for all services, and where the whole repository ends up in the build context and the final image.

How does generatePackageJson create a pruned lockfile for each service?

…the packages that service actually uses. With generatePackageJson enabled on Nx's Node-oriented build executors, Nx produces that context as part of the build.

What Nx computes

At build time, Nx walks the project graph from the app's entry point through every workspace library it depends on and collects the external npm packages those files import. It writes a package.json into the build output that lists only those packages. Version specifiers come from the root package.json, so the service declares the same range the rest of the monorepo uses. A lodash import that exists only in some other app's library never reaches this manifest.

Next to it, Nx writes a pruned lockfile. Nx takes the root lockfile and drops every entry that isn't reachable from the service's dependencies, including transitive ones. The resolved versions, integrity hashes and tarball locations in the entries it keeps are copied from the root lockfile.

That is why the install inside Docker should be a frozen or CI-style install (npm ci, or the --frozen-lockfile/immutable mode of Yarn or pnpm). A plain install could re-resolve ^4.18.0 to whatever is newest today. A frozen install refuses to change the lockfile, so the image gets the exact versions you tested against in the workspace.

workspace project graph
        │  (build with generatePackageJson)
        ▼
dist/apps/<app>/
  ├── main.js        compiled code
  ├── package.json   only imported third-party deps
  └── <lockfile>     pruned from root
        │  (used as docker build context)
        ▼
frozen install + copy code
        ▼
per-service image

The lockfile's name and format depend on your package manager. Exact behavior has changed across Nx releases. Build one app and inspect its output directory before you write the Dockerfile against it.

┌─────────────────────┐   ┌──────────────────┐   ┌──────────────────────┐
│ project graph       │   │ root package.json│   │ root lockfile        │
│ app + workspace libs│   │ version ranges   │   │ resolved + integrity │
└──────────┬──────────┘   └────────┬─────────┘   └──────────┬───────────┘
           │ imports used          │ ranges                 │ entries
           └───────────────────────┼────────────────────────┘
                                   ▼
                    ┌───────────────────────────────┐
                    │ nx build (generatePackageJson)│
                    │ collect deps + prune lockfile │
                    └───────────────┬───────────────┘
                                    ▼
                    ┌───────────────────────────────┐
                    │ dist/apps/<app>/              │
                    │  main.js       compiled code  │
                    │  package.json  imported deps  │
                    │  <lockfile>    pruned subset  │
                    └───────────────┬───────────────┘
                                    │ docker build context
                                    ▼
                    ┌───────────────────────────────┐
                    │ Dockerfile                    │
                    │  1. copy manifest + lockfile  │
                    │  2. frozen install, copy code │
                    └───────────────┬───────────────┘
                                    ▼
                    ┌───────────────────────────────┐
                    │ per-service image             │
                    │ root-resolved versions only   │
                    └───────────────────────────────┘

With generatePackageJson, Nx combines the project graph, root package.json ranges and root lockfile entries into a per-app dist folder whose pruned lockfile drives a frozen install in Docker; file names and pruning details vary by package manager and Nx version.

How do you enable generatePackageJson and verify the dist output?

Open the service's build target and set generatePackageJson to true in its options. Where this goes depends on how the target is defined. For an explicit executor such as webpack or esbuild, it belongs in the target's options in project.json. For an inferred target, it goes in the plugin options in the project's bundler config. Then build the single service with nx build api, substituting your project name.

Open the build's output path, commonly dist/apps/<app>, and check three things:

  • A package.json exists. Its dependencies should list only the third-party packages this service imports. If you see packages that belong to other apps, something in the import graph is pulling them in. A barrel file that re-exports an entire library is a common cause.
  • A lockfile matches your package manager. Look for package-lock.json, yarn.lock, or pnpm-lock.yaml. If it is missing, the Docker install can't be reproducible.
  • The lockfile installs cleanly. Copy the two files to a scratch directory and run your package manager's frozen install, such as npm ci. This catches pruning errors before CI does.

Internal workspace libraries can show up in the output in one of two ways. If the bundler resolves them through TypeScript path aliases, their code is compiled into the output bundle and they don't appear in package.json. If they are buildable libraries treated as external, they appear as dependencies that point at workspace packages. A registry can't resolve those, so the install inside a container fails. The Dockerfile in the next section assumes the bundled approach, so confirm that no internal package names appear in the generated dependency list.

#!/usr/bin/env bash
# Build one service and check its generated package.json and lockfile.
# Assumes an npm workspace, a project named 'api', and internal libs scoped '@acme/'.
set -euo pipefail

APP=api
OUT=dist/apps/$APP
SCOPE=@acme/

# Bypass the cache so the files reflect the current config.
npx nx build "$APP" --skip-nx-cache

# 1. package.json must exist. Print its dependencies for review.
test -f "$OUT/package.json" || { echo "missing $OUT/package.json"; exit 1; }
node -e 'console.log(Object.keys(require(process.argv[1]).dependencies || {}).join("\n"))' \
  "$PWD/$OUT/package.json"

# 2. A lockfile for the package manager must exist (npm here).
test -f "$OUT/package-lock.json" || { echo "missing lockfile"; exit 1; }

# 3. Internal libraries must be bundled, not listed as dependencies.
#    A registry cannot resolve them inside the container.
if grep -q "\"$SCOPE" "$OUT/package.json"; then
  echo "internal package found in dependencies; bundle it via path aliases"
  exit 1
fi

# 4. Frozen install in a scratch directory, the same way the Dockerfile will run it.
SCRATCH=$(mktemp -d)
cp "$OUT/package.json" "$OUT/package-lock.json" "$SCRATCH/"
(cd "$SCRATCH" && npm ci --ignore-scripts)
echo "OK: $APP output installs cleanly from its pruned lockfile"
rm -rf "$SCRATCH"

A verification script that builds one service with generatePackageJson enabled, checks that dist/apps/api contains a package.json and a lockfile with no internal workspace packages, and confirms the pruned lockfile passes a frozen npm ci in a scratch directory.

Writing a multi-stage Dockerfile per Nx service

With that confirmed, the Dockerfile needs two stages. The deps stage starts from a Node base image, copies only the generated package.json and pruned lockfile, and runs a frozen production install (npm ci --omit=dev or your package manager's equivalent). Copying just those two files first means Docker reuses the cached install layer until the service's dependencies change, so a code-only change skips the install. A frozen install also fails when the lockfile and manifest disagree, so drift shows up as a build error instead of a silently different dependency tree.

The runtime stage starts from a slim Node image, copies node_modules from the deps stage and the compiled output from dist/<app>, and switches to a non-root user before the CMD. Official Node images include a node user for this. Without it, a compromised process runs as root inside the container.

Keep the build context small

Use dist/<app> as the build context so Docker only sends the built service. If you build from the repo root, add a .dockerignore that excludes source directories, other apps, and the root node_modules. Otherwise every build uploads the entire monorepo, and unrelated edits can invalidate cached layers.

Match base images across stages

Native modules compile against the libc and CPU architecture of the deps stage. A binary built on a glibc image won't load on Alpine's musl, and an amd64 build won't load on arm64. Use the same image family and target platform in both stages.

Smoke test before pushing

Start the container and hit its health endpoint. For workers that have no HTTP endpoint, run node -e "require('<entry>')" inside the image. Either check fails immediately on a Cannot find module error, which is the most common way a pruned install breaks, and you catch it before deploy.

# Build context is dist/apps/api, which holds main.js plus the
# generated package.json and pruned package-lock.json.
#   docker build -t api:local dist/apps/api

# Both stages use the same image family (Debian/glibc) so native
# modules compiled here load at runtime. Pin the platform in CI.
FROM node:20-bookworm-slim AS deps
WORKDIR /app
# Copy only the manifests so this layer stays cached until deps change.
COPY package.json package-lock.json ./
# Frozen install: fails if lockfile and manifest disagree.
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 . .
# Official Node images ship a non-root 'node' user.
USER node
EXPOSE 3000
CMD ["node", "main.js"]

# Smoke test before pushing:
#   docker run -d --name api-smoke -p 3000:3000 api:local
#   curl -fsS
#   docker rm -f api-smoke
# For workers without HTTP, catch missing-module errors directly:
#   docker run --rm api:local node -e "require('./main.js')"

A two-stage Dockerfile for one Nx service: a cached frozen production install from the pruned lockfile, a slim non-root runtime on a matching glibc base, and smoke-test commands.

How do you build only affected service images in CI?

Run nx affected -t build with explicit --base and --head values so Nx compares the right commits and builds only the services whose project graph changed. A change to a shared library marks every project that depends on it as affected. A change confined to one service's source affects only that service. To get the image builds into the same graph, add a docker target to each service's project.json that runs docker build against that service's Dockerfile and declares dependsOn: ["build"]. Then nx affected -t docker builds the dist output and the image in the correct order, and Nx skips everything else.

Getting the base commit right

The affected calculation is only as good as its base. On a pull request, use the merge base with the target branch. On the main branch, use the last commit that passed CI, not simply HEAD~1. If a previous pipeline failed, HEAD~1 drops that commit's changes, and the images it touched are never rebuilt. Shallow clones cause a related failure. If the base commit is not fetched, the diff is wrong. Fetch enough history for the comparison to resolve.

What it costs and where the savings come from

Per-service images multiply three things:

  • CI minutes
  • Registry storage
  • The number of images your vulnerability scanner processes

Affected builds offset this cost in three ways:

  • Fewer rebuilds: a typical commit rebuilds a few images instead of all of them.
  • Stable install layers: each pruned lockfile changes only when that service's dependencies change, so the install layer stays cached across unrelated commits.
  • Smaller layers: the layers that do change are smaller, so they push and pull faster.

When should you avoid generatePackageJson, and what can it miss?

Nx builds the generated package.json from the project graph, and the project graph comes from static analysis of import statements. Anything the analyzer cannot resolve to a literal module name is silently left out. The build still passes and the image still builds. The failure only appears at container startup, or later when a rarely used code path runs. Common gaps:

  • Dynamic imports and requires built from variables, such as require(\./drivers/${name}`)` or a plugin name read from an environment variable.
  • Config-driven runtime plugins, for example ORM drivers, logging transports or Babel/PostCSS plugins named only in a JSON or YAML file.
  • Peer dependencies, which a library expects the host to provide but your code never imports directly.
  • Native modules, where the package may be detected but its build toolchain or libc expectations (glibc vs. musl on Alpine) are not met in the runtime image.

The fix is to make these dependencies visible. Declare them in the project's own package.json, or add a side-effect import in the service's entry file so the analyzer sees them. Then add a CI smoke test that starts the container and exercises each plugin path.

There are also structural limits. Versions come from the root lockfile, so one service cannot pin a different version than the rest of the workspace. When dist is built on a CI runner and then copied into the image, the artifact depends on that runner's Node version and cache state. This makes provenance harder to audit than a build that runs entirely inside Docker. For heavily plugin-driven services, or for teams that require hermetic in-Docker builds, the approach is a poor fit.

What are the alternatives to pruned per-service images, and who should use each?

Four approaches cover most Nx monorepos. They make different trade-offs between image size, rebuild speed and how much of the build you can reproduce from the Dockerfile alone.

Approach Image size Layer caching Hermeticity Build context Native modules Maintenance
Naive full-repo install Largest; every workspace dependency ships Any root lockfile change invalidates the install layer High Whole repo Built in-image, matches runtime Low
generatePackageJson + pruned lockfile Small; only this service's deps Invalidated only when this service's deps change Low; build runs on the host or CI runner dist folder only Built in-image from pruned manifest Moderate; watch for missed dependencies
Full Nx build inside Docker Small runtime stage, heavy build stage Builder layer busts on most source changes Highest Whole repo Built in-image Moderate; tuning ignore files and cache mounts
Bundled app, minimal node_modules Smallest Bundle layer changes on every code edit, but it is one small layer Depends on where bundling runs dist folder only Must be marked external and installed separately Higher; bundler config, source maps, dynamic require

Bundling has hidden costs. A .node binary can't be inlined, so you still need a partial install for those packages. Stack traces point at a single generated file unless you ship source maps and start Node with --enable-source-maps. Libraries that resolve files at runtime can also break silently.

Which one fits

  • Small team, few services: use the naive install, which is simple to maintain.
  • Many services on a shared lockfile: use the pruned lockfile approach, which keeps images small and rebuilds focused.
  • Compliance-driven or plugin-heavy builds: run the full Nx build inside Docker.
  • Latency-sensitive functions with no native dependencies: use bundling.

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