What does nx docker build affected mean, and how does Nx decide what changed?

"Nx docker build affected" means treating a container image as one more Nx target, usually named docker-build, that sits beside build, test and lint on each deployable backend project. You then run nx affected -t docker-build instead of building every image on every commit. Nx builds images only for projects whose code, or whose dependencies' code, changed.

Nx decides what changed in three steps:

  1. Diff. It compares a base SHA with a head SHA (by default HEAD). For a pull request, the base resolves to the merge-base with your default branch, so the diff contains only commits made on the branch.
  2. Map files to projects. Each changed path maps to the project that owns it. Changes to the lockfile or other workspace-level files can affect many projects at once.
  3. Walk the project graph. If libs/auth changed, every app that imports it is also affected, even if the app's own folder is untouched.

The full flow:

git diff (base…head) → changed files → owning projects → dependents via project graph → affected projects with a docker-build target → build, tag, push to registry

Everything depends on the base. CI runners often do shallow clones, and a shallow clone can lack the commits needed to compute a merge-base. When that happens, the comparison fails or gives the wrong answer, so fetch enough history.

On main, use the SHA of the last successful pipeline as the base, not simply HEAD~1. If a previous run failed, its changes were never shipped. Diffing from the last green build includes those changes again, so the failed images get rebuilt.

 +-------------------------+     +-------------------------+
 | PR: base = merge-base   |     | main: base = SHA of     |
 |   with default branch   |     |   last green pipeline   |
 +-------------------------+     +-------------------------+
              |                                |
              +---------------+----------------+
                              v
          +----------------------------------------+
          | git diff base...head (head = HEAD)     |
          | (fetch enough history; avoid shallow)  |
          +----------------------------------------+
                              v  changed files
          +----------------------------------------+
          | map changed paths to owning projects   |
          | (lockfile/workspace file -> many)      |
          +----------------------------------------+
                              v  owning projects
          +----------------------------------------+
          | walk project graph to dependents       |
          | libs/auth -> every app that imports it |
          +----------------------------------------+
                              v  affected projects
          +----------------------------------------+
          | affected projects with docker-build    |
          | -> build, tag, push each image         |
          +----------------------------------------+
                              v
          +----------------------------------------+
          | container registry                     |
          +----------------------------------------+

How nx affected -t docker-build resolves a base SHA, diffs it against head, maps changed files through the project graph, and builds and pushes images only for affected projects.

Who should use affected image builds, and when should you avoid them?

This approach fits backend and platform engineers who run several deployable services from one Nx monorepo and whose CI currently builds and pushes every image on every commit. If most commits touch one or two services but the pipeline rebuilds all of them, you pay for image builds, registry pushes and vulnerability scans that produce byte-for-byte equivalent artifacts. Affected builds cut that work down to the services a change can actually reach.

The usual alternative is hand-written path filters in the CI config, such as "rebuild orders-api when apps/orders-api/** or libs/payments/** changes." These filters capture dependencies at the moment someone writes them. When a developer adds an import from a new shared library, nothing updates the filter, and the service ships stale code until someone notices. Nx builds the project graph from source imports and project configuration, so a new dependency is picked up as soon as the code that uses it is committed. You stop maintaining a second, manually synced copy of your dependency graph in YAML.

Skip it in these cases:

  • One or two services. The graph analysis and tagging logic cost more to maintain than building everything.
  • Dependencies the graph cannot see. If services load config files, plugins or modules at runtime by path or computed name, Nx will not link them. Changes to those files will not trigger rebuilds.
  • No reliable way to resolve deployed tags per service. When only some images are rebuilt, your deploy step must look up the current tag for every service it did not rebuild. If you cannot do that reliably, partial builds will cause inconsistent releases.

How do you define a docker-build target with inputs and dependsOn?

Each backend app gets its own docker-build target in its project.json. The target uses the nx:run-commands executor to call docker build with the app's Dockerfile and a build context. Set dependsOn to ["build"] so Nx compiles the app before Docker runs. The Dockerfile then copies finished output from dist/ instead of compiling inside the image.

The inputs decide when the image counts as affected. Define a production named input in nx.json that includes the project's files and excludes spec files, test configs and Markdown. Then give docker-build these inputs:

  • production, for the app's own runtime code.
  • ^production, for the runtime code of the shared libraries it depends on.
  • {projectRoot}/Dockerfile and any .dockerignore.

With this set, editing a test or a README leaves the image unaffected. Changing a shared library's source does mark it affected.

Set cache: false on this target. The image's real output is a tag in a registry, not files Nx can restore. If Nx registers a cache hit, it replays the logs and skips the command, including the push. The deploy step then looks for a tag that was never pushed.

Keep inputs narrow. If you list the root lockfile, nx.json or a shared tsconfig.base.json as a file input, every edit to that file rebuilds every image. For package changes, rely on Nx's own lockfile analysis, which only affects the projects that use the changed packages.

Nx's container plugin can generate and run these targets for you, with build arguments, tags and registry settings as target options. Option names and defaults have changed between releases, so check them against the docs for your Nx version.

{
  "name": "api",
  "projectType": "application",
  "sourceRoot": "apps/api/src",
  "targets": {
    "docker-build": {
      "executor": "nx:run-commands",
      "dependsOn": ["build"],
      "cache": false,
      "inputs": [
        "production",
        "^production",
        "{projectRoot}/Dockerfile",
        "{projectRoot}/.dockerignore"
      ],
      "options": {
        "parallel": false,
        "commands": [
          "docker build -f apps/api/Dockerfile -t registry.example.com/acme/api:latest .",
          "docker push registry.example.com/acme/api:latest"
        ]
      }
    }
  }
}

A project.json docker-build target that builds the app first, runs build and push in order, marks the image affected only by runtime code, shared library code and Docker files, and disables caching so the push always runs.

How should a multi-stage Dockerfile be structured around Nx build output?

Order the Dockerfile so the slow, rarely changing work happens first. Docker invalidates every layer after the first instruction whose inputs changed. If the compiled app is copied in before dependencies are installed, every code change triggers a full reinstall.

The docker-build target depends on build, so compilation happens in Nx on the runner, not inside Docker. The Dockerfile only packages the result:

  1. Dependency stage: copy only the manifest and lockfile from the app's build output, then run a clean install of production dependencies (for example, npm ci --omit=dev). This layer stays cached until those two files change.
  2. Runtime stage: start from a slim base image, copy node_modules from the dependency stage, then copy the compiled bundle last. Code-only commits rebuild just this final layer.

Which manifest you copy decides how far a dependency change spreads. If every image copies the root package.json and lockfile, adding a library to one service changes the lockfile and invalidates the install layer for every app in the monorepo. Nx's webpack and esbuild executors can emit a pruned package.json, and a matching lockfile, into the output directory. The option is generatePackageJson; check your executor's schema. With pruned files, each image's install layer depends only on that app's dependency graph.

The trade-off is that pruning relies on static analysis of imports. It can miss:

  • dynamic require calls
  • peer dependencies
  • packages loaded by a framework at runtime
  • platform-specific optional binaries

The pruned lockfile can also resolve differently from the root lockfile. The build passes, and the container fails on startup or on a rarely used code path. To catch this in CI, start each built image and hit a health endpoint before pushing it.

# Build context: repo root. Nx has already run `build` with generatePackageJson,
# so dist/apps/api contains main.js plus a pruned package.json and lockfile.
ARG APP_DIST=dist/apps/api

# ---- Dependency stage ----
FROM node:20-slim AS deps
ARG APP_DIST
WORKDIR /app
# Copy ONLY the pruned manifest and lockfile. This layer's cache key depends
# on this app's dependency graph, not the root lockfile.
COPY ${APP_DIST}/package.json ${APP_DIST}/package-lock.json ./
# Clean, reproducible install of production deps only.
RUN npm ci --omit=dev

# ---- Runtime stage ----
FROM node:20-slim AS runtime
ARG APP_DIST
ENV NODE_ENV=production
WORKDIR /app
# Reuse the cached install from the deps stage.
COPY --from=deps /app/node_modules ./node_modules
# Compiled bundle goes last: code-only commits rebuild just this layer.
COPY ${APP_DIST}/ ./
USER node
EXPOSE 3000
CMD ["node", "main.js"]

A two-stage Dockerfile that installs production dependencies from the Nx-generated pruned package.json and lockfile before copying the compiled bundle, so code changes reuse the cached install layer.

How do you make Docker layer caching work on ephemeral CI runners?

Ephemeral runners start with an empty Docker cache, so every layer is rebuilt unless you supply a cache from somewhere else. BuildKit reuses a layer only when that instruction and every instruction before it are unchanged. Order the Dockerfile from least to most volatile: base image, then the app's package.json and lockfile, then the dependency install, and finally the Nx build output from dist. A source-only change then invalidates just the last COPY, and the expensive install layer is restored from cache.

To persist layers between runs, pass --cache-to and --cache-from to docker buildx build. With type=registry,ref=<repo>:buildcache, the cache is stored as a separate artifact next to your images. Add mode=max to export the intermediate stages of a multi-stage build as well. The default mode=min exports only the layers in the final image, which leaves out the builder stage where most of the time goes. Some CI systems provide their own cache backend that works the same way. Use one cache ref per app so that unrelated services don't overwrite each other's cache.

The cache has costs. Every run uploads and downloads cache layers, and the cache refs use registry storage until you prune them.

Illustrative estimate: say a service's mode=max cache is 600 MB, the runner pulls at 40 MB/s, and the dependency install takes 120 s. Pulling the cache takes about 15 s, a clear win. For a small service with 80 MB of dependencies on a 10 MB/s runner that builds from scratch in 10 s, pulling the cache (about 8 s plus overhead) saves little or nothing. Measure both cases before you enable caching everywhere.

#!/usr/bin/env bash
# Build and push images for affected apps, reusing BuildKit layers from a
# registry cache so an ephemeral runner does not start from zero.
set -euo pipefail

REGISTRY="registry.example.com/acme"   # placeholder registry/namespace
TAG="${GIT_SHA:-dev}"                   # image tag, e.g. the commit SHA

# The default 'docker' driver cannot export a cache to a registry,
# so create a builder that uses the docker-container driver.
docker buildx create --name ci-builder --driver docker-container --use

# Only apps touched by this change (compares against the Nx base ref).
for app in $(npx nx show projects --affected --type=app); do
  # Produce dist/apps/$app before the image copies it in.
  npx nx build "$app"

  # One cache ref per app, so services never overwrite each other's cache.
  CACHE_REF="$REGISTRY/$app:buildcache"

  # --cache-from: pull layers exported by an earlier run (a miss is not fatal).
  # --cache-to mode=max: export the builder stage too, not just final layers.
  docker buildx build \
    --file "apps/$app/Dockerfile" \
    --tag "$REGISTRY/$app:$TAG" \
    --cache-from "type=registry,ref=$CACHE_REF" \
    --cache-to "type=registry,ref=$CACHE_REF,mode=max" \
    --push \
    .
done

A CI script that builds only the affected Nx apps. Each app imports and exports its own BuildKit registry cache with mode=max, so the builder stage, including the dependency install, survives between ephemeral runners.

Running affected image builds in CI: base SHAs, parallelism, tagging and deploy

Start by fetching full git history on the runner. A shallow clone makes Nx fail or fall back to treating everything as affected, depending on how the comparison breaks. Set --head to the commit under test. Set --base to the SHA of the last successful pipeline on the main branch, not simply the previous commit. If you use the previous commit, a failed run's changes never get rebuilt because the next run compares against a commit that was never shipped. Then run nx affected -t docker-build with --parallel capped at two or three. Image builds saturate CPU, memory and disk I/O. Running too many on one runner slows every build and can exhaust disk space mid-push.

Tag each built image twice. The commit SHA tag is immutable and gives you traceability and rollback. A stable tag such as main moves to the latest build. After pushing, write the affected project names and their SHA tags to a file and pass it to deploy jobs as an artifact. For services not in that list, deploy resolves the stable tag to its current digest in the registry and deploys that digest, so every release pins exact images.

Force-pushes are the main hazard. They can leave the recorded base SHA unreachable or wrong, and affected may then silently skip services. Fail the pipeline if the base commit is missing. Separately, schedule a nightly or weekly run-many rebuild of every image so unchanged services still pick up patched base images.

The setup takes a few days of pipeline work and ongoing upkeep of target inputs. It pays off once most commits touch only a few services.

What are the alternatives to Nx affected Docker builds?

Nx affected builds are one of several ways to avoid rebuilding unchanged images. Each alternative trades accuracy against effort differently.

Approach Accuracy Maintenance CI cost Deploy and audit Typical failure mode
Nx affected targets High; follows the project graph Medium; target inputs must stay correct Low Partial tag sets per commit Missing input leaves a stale image
CI path filters Medium; globs miss shared libraries High as dependencies grow Low Partial tag sets Shared code change skips dependent services
Build every image Total Low High, grows with service count One tag for everything Slow pipelines, queued runners
Layer caching alone Total Low Medium; every build still runs, cache hits are cheap One tag for everything Cache misses on ephemeral runners erase savings
Per-service repositories High per repo High; cross-repo version bumps Low per repo Independent histories, harder to trace a cross-service change Services drift onto different library versions

Path filters work when services share almost no code. They break down once services share libraries, because each glob has to list the dependency tree by hand.

Building everything is the right default below roughly a handful of services or when builds take only a few minutes. Every deploy has one consistent tag, so audits stay simple.

Layer caching alone suits teams with persistent builders or a reliable registry cache. Docker still checks every layer, so correctness is never at risk.

Per-service repositories fit teams that already deploy and version independently. Do not split a monorepo only to save CI minutes.

Choose Nx affected builds when shared libraries are common, the service count is growing, and someone owns the target inputs.

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