How does nx affected decide which Docker images to build?

nx affected starts with a Git diff between a base and a head commit. Nx maps each changed file to the project whose root contains it, then walks the project graph in reverse to add every project that depends on the touched ones. It then runs the target you asked for, such as docker-build, only on that set.

git diff base..head
  libs/auth/src/token.ts
        │
        ▼
  project graph:  auth ◄── api-gateway
                  auth ◄── billing-svc
                  (orders-svc does not import auth)
        │
        ▼
  affected: auth, api-gateway, billing-svc
        │
        ▼
  docker-build / docker-push → api-gateway, billing-svc

A change to a shared library rebuilds every service that imports it. Those services bundle the library's code into their images, so an image built before the change contains stale code. Skipping it would deploy a mismatch.

The graph only knows about dependencies it can see in source imports and project configuration. It misses several common inputs:

  • A shared Dockerfile kept outside the service directories.
  • A base image definition.
  • .env files and runtime config templates.
  • Plugins or modules loaded by path at runtime.

None of these show up as import edges, so changing them affects no service.

You can close these gaps in two ways:

  • Make the dependency visible to nx affected. Give the shared asset its own Nx project, for example a docker-base project. Then list it under each service's implicitDependencies. That adds a graph edge, so changes to the asset now mark the services as affected.
  • Make the dependency visible to the cache. Add the file to the docker-build target's inputs. Nx then includes it in the cache hash and won't reuse a stale cached build.
  git diff base..head
  ┌─────────────────────────┐
  │ libs/auth/src/token.ts  │
  └────────────┬────────────┘
               │ map changed file to owning project root
               ▼
  ┌──────────────────────────────────────────────┐
  │ project graph (dependents walked in reverse) │
  │                                              │
  │   api-gateway ──► auth ◄── billing-svc       │
  │                                              │
  │   orders-svc  (no edge to auth)              │
  └────────────┬─────────────────────────────────┘
               │ affected: auth, api-gateway, billing-svc
               ▼
  ┌──────────────────────┐  ┌──────────────────────┐
  │ api-gateway          │  │ billing-svc          │
  │ docker-build/push    │  │ docker-build/push    │
  └──────────────────────┘  └──────────────────────┘

  Blind spots: no import edge, so nothing is affected unless declared
  ┌───────────────────────────────┐
  │ shared Dockerfile, base image,│  implicitDependencies
  │ .env, runtime config, plugins ├──────────────────► each service
  │ loaded by path (docker-base)  │  inputs on docker-build
  └───────────────────────────────┘

A diff in libs/auth maps to the auth project, and the reversed graph marks api-gateway and billing-svc affected, but orders-svc is skipped. Assets with no import edge need implicitDependencies or inputs.

Who should use affected-only image publishing, and when should you avoid it?

Affected-only publishing fits a specific shape of repository: a monorepo with many independently deployable services, image builds that take minutes rather than seconds, and shared libraries that only some services import. Under those conditions, most commits touch a small slice of the graph, so skipping untouched services saves real build time, registry storage and deploy churn.

The approach pays off most when:

  • Services deploy independently. Each service has its own release cadence, and pushing an unchanged image only adds noise to rollouts and audit trails.
  • Builds are expensive. Compiling native dependencies or running multi-stage builds per service makes every skipped build count.
  • The dependency graph is sparse. Libraries are scoped to a few consumers instead of being imported everywhere.

When to avoid it

With three services and builds that finish in under a minute, a full rebuild with good layer caching is usually simpler, and it rarely builds the wrong thing. If a core package such as logging or config is imported by every service, most commits mark everything as affected and the benefit shrinks to near zero. The approach also carries ongoing costs. You have to maintain a reliable base commit, declare implicit dependencies, and debug "why didn't this rebuild?" incidents.

Approach Change detection Main cost Best fit
Full rebuild + layer caching None; cache skips unchanged layers Wasted CI minutes at scale Few services, fast builds
Hand-maintained CI path filters Glob patterns per service Filters drift from real imports Stable, rarely changing layouts
Per-service repositories Repository boundary Cross-repo library versioning Teams with strong ownership splits
Nx affected Project graph from imports and config Base-commit state, graph upkeep Large monorepos with shared libraries

How do you model a service as an Nx project with docker-build and docker-push targets?

Give each service two targets in its project.json. docker-build declares dependsOn on the project's own build target, so Nx compiles the app before Docker copies dist into the image. docker-push depends on docker-build. Running nx affected -t docker-push therefore pulls in the whole chain for every affected service and skips the rest.

Nx can only judge a project affected, or a cache entry valid, by the inputs you declare. Add the service's Dockerfile, its .dockerignore, and any shared files outside the project directory to docker-build inputs, such as a common base Dockerfile or entrypoint script referenced with {workspaceRoot}. If you omit them, a change to the shared base image will not rebuild anything.

Enable caching only where outputs are deterministic and restorable. A compiled dist folder qualifies. A docker build result usually does not, because the image lives in the local daemon, not in a file Nx can restore. Set docker-push to cache: false without exception. A cache hit replays the stored terminal output and reports success, but it says nothing about whether the image exists in the registry today.

Keep each build context small:

  • Add a per-service .dockerignore that excludes the rest of the monorepo.
  • Where your build executor supports it, emit a pruned package.json and lockfile alongside dist, so dependency installation only sees what that service needs.
  • Use multi-stage builds that copy only the built artifacts into the final stage.

Without these, unrelated file changes invalidate the layer cache, and source code from other services can end up in your images.

{
  "name": "orders-api",
  "targets": {
    "docker-build": {
      "executor": "nx:run-commands",
      "dependsOn": ["build"],
      "inputs": [
        "default",
        "{projectRoot}/Dockerfile",
        "{projectRoot}/.dockerignore",
        "{workspaceRoot}/docker/base.Dockerfile",
        "{workspaceRoot}/docker/entrypoint.sh"
      ],
      "cache": false,
      "options": {
        "command": "docker build -f apps/orders-api/Dockerfile -t registry.example.com/orders-api:{args.tag} dist/apps/orders-api"
      }
    },
    "docker-push": {
      "executor": "nx:run-commands",
      "dependsOn": ["docker-build"],
      "cache": false,
      "options": {
        "command": "docker push registry.example.com/orders-api:{args.tag}"
      }
    }
  }
}

project.json for one service: docker-build depends on build and declares the Dockerfile, .dockerignore and shared base files as inputs, uses the dist folder as a small build context, and both Docker targets disable caching.

How should you tag images so deployments stay immutable and traceable?

Every image gets a tag derived from the full or short commit SHA it was built from. That tag is never reused, so a deployment manifest that references it always resolves to the same bytes, and anyone can map a running container back to the exact source. A semantic version tag is optional and serves people who want to read release history.

Mutable tags such as latest or a branch name should not drive deployments. When latest moves, a node that restarts or scales out can pull a different image than its neighbours. A rollback that points at latest does not roll anything back. If your registry can enforce tag immutability, turn it on for SHA and version tags.

Tag type Mutability Intended use
Commit SHA Immutable Deployments, rollbacks, audit trail
Semantic version Immutable by policy Human-readable releases, changelogs
latest / branch name Mutable Local development convenience only

To get versions, configure nx release with independent project relationships. With conventional commits enabled, Nx reads the commit messages that touch each project, bumps only the projects that changed, and creates a git tag per project. If a team prefers explicit control, it can specify the bumps directly instead. The publish step then reads the git tag at the release commit and applies the version as a second image tag next to the SHA.

Keep the two steps separate. Versioning and git tagging should succeed or fail independently of registry pushes, which makes a failed push safe to retry.

This approach has costs. Independent versioning produces many versions and many changelogs. Conventional commits also only work if the whole team agrees on the format and enforces it in review or with a commit linter.

#!/usr/bin/env bash
set -euo pipefail

# --- Release step (its own CI job) ---
# nx.json sets release.projectsRelationship to "independent" and enables
# conventional commits, so only projects with relevant commits get a bump,
# a changelog entry, and a git tag such as "api@1.4.0".
npx nx release --skip-publish --yes
# For explicit control instead of commit parsing:
#   npx nx release version minor --projects=api

# --- Publish step (separate job, safe to retry) ---
# Run against the release commit. It only reads git tags and never versions anything.
REGISTRY="registry.example.com/acme"
SHA="$(git rev-parse --short=12 HEAD)"

# Only projects released at this commit have a tag here, so unchanged
# services are skipped. This assumes unscoped names in the tag pattern
# {projectName}@{version}.
for tag in $(git tag --points-at HEAD); do
  project="${tag%@*}"
  version="${tag##*@}"
  image="${REGISTRY}/${project}"

  # The immutable SHA tag drives deployments. The version tag is for people.
  docker build \
    -t "${image}:${SHA}" \
    -t "${image}:${version}" \
    -f "apps/${project}/Dockerfile" .

  docker push "${image}:${SHA}"
  docker push "${image}:${version}"
  # No :latest push. Deploy manifests reference ${image}:${SHA}.
done

The release job runs nx release to version and tag only the changed projects, and a separate publish job turns each git tag at the release commit into an image pushed under both its commit-SHA tag and its semantic version tag.

Which base and head commits should CI use for nx affected?

The default many teams reach for, comparing HEAD~1 to HEAD, only works if every pipeline succeeds. Suppose commit A changes the billing service and its pipeline fails at the push step. Commit B touches only orders. When B's pipeline compares against HEAD~1, it sees only B's diff. billing is never rebuilt, and nothing reports the gap.

A safer base is the SHA of the last successful deploy from main. Every commit since that point counts as affected, however many pipelines failed in between. The trade-off is that you now have state to manage. Something has to record that SHA after a successful run, such as a git tag, a CI variable, or an object in artifact storage. That record has to be written only after the push succeeds, protected from concurrent pipelines overwriting each other, and kept up to date when the deploy process changes.

Affected detection also needs git history. A shallow clone with depth 1 does not contain the base commit, so the diff fails or produces nonsense. Fetch full history, or at least enough depth to reach the stored SHA.

Some cases will always come up:

  • First run: no SHA has been recorded yet.
  • Garbage-collected base: the commit no longer exists.
  • Force-push: the base is no longer an ancestor of HEAD.

In each case, building all projects is the correct fallback. The script below resolves the base, confirms with git merge-base --is-ancestor that it is reachable from HEAD, and otherwise runs nx run-many -t docker-build instead of nx affected --base=$BASE --head=$HEAD.

#!/usr/bin/env bash
set -euo pipefail

# Tag that marks the last commit on main that built AND pushed successfully.
TAG="deploy/main-last-success"
HEAD_SHA=$(git rev-parse HEAD)

# Affected detection needs history back to the base. Undo a shallow CI clone.
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
  git fetch --unshallow origin
fi
# Fetch the marker tag; --force picks up a tag that was moved since the last fetch.
git fetch --force origin "refs/tags/$TAG:refs/tags/$TAG" 2>/dev/null || true

BASE_SHA=$(git rev-parse --verify --quiet "refs/tags/$TAG^{commit}" || true)

# Fallback cases: first run (no tag), base commit gone, or force-push made
# the base unreachable from HEAD. In all of them, rebuild everything.
if [ -z "$BASE_SHA" ] \
  || ! git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null \
  || ! git merge-base --is-ancestor "$BASE_SHA" "$HEAD_SHA"; then
  echo "No usable base; building all projects"
  npx nx run-many -t docker-build
else
  echo "Building projects affected between $BASE_SHA and $HEAD_SHA"
  npx nx affected -t docker-build --base="$BASE_SHA" --head="$HEAD_SHA"
fi

# Reached only if the build/push above succeeded (set -e).
# Run this job in a single-concurrency group so two pipelines on main
# cannot move the tag out of order.
git tag --force "$TAG" "$HEAD_SHA"
git push --force origin "refs/tags/$TAG"

A CI script that uses a git tag to track the last successful main-branch deploy as the nx affected base, unshallows the clone so that base commit exists locally, and builds every project when the tag is missing, the commit is gone, or a force-push made it unreachable from HEAD.

Wiring nx affected docker publish into a CI pipeline

Compute the affected list once

Resolve base and head at the start of the job, run nx show projects --affected with a filter for projects that define docker-build, and save the result as a pipeline artifact. Every later step reads that file. If each step recalculated the list, a retried job or a moved branch could produce a different set of projects, and the published images would no longer match the manifest.

Authenticate, then build with a bounded parallelism

Run docker login before any Nx target so a credentials failure stops the job before any build work starts. Then run nx affected -t docker-build docker-push and set --parallel deliberately. Each concurrent build holds a full layer cache in memory, and each push counts against the registry's request quota. On a runner with 8 GB of RAM, three or four parallel builds is a reasonable starting point (illustrative estimate). Tune it after you watch real memory use and any registry throttling responses.

Have the push target append the service name, tag and digest to a JSON file. Downstream jobs should read that file and not parse build logs.

Carry forward unaffected tags

Generate the deploy manifest by merging the new JSON over the previous manifest. Unaffected services keep their last pinned tag. This way the manifest always names an exact image for every service. Rollback becomes a revert of one file, and promotion to another environment means copying a manifest that has already been tested.

Schedule full rebuilds

Base image and OS security patches never appear in a git diff. Add a nightly or weekly job that runs docker-build and docker-push for all projects, with base image pulls forced.

How do you verify the setup, and how much engineering time does it save?

Verify before trusting it

Run three checks before you rely on the pipeline.

  1. Check the affected list on a pull request. Run nx show projects --affected with the same --base and --head values CI uses, and compare the output to the services you expected. Test one change to a shared library and one change to a single service. If the shared-library change does not list every consumer, the graph is missing an edge.
  2. Inspect the graph for that change. nx graph --affected shows why each project was selected. Look for implicit dependencies you never declared, such as a root Dockerfile or a config file outside any project's inputs.
  3. Audit the registry after a run. Query each repository's tag list, for example through the registry's /v2/<name>/tags/list endpoint. Affected services should have exactly one new SHA tag each. Unaffected services should have none. An extra tag means the selection is too broad. A missing tag means an affected service was skipped silently.

What it saves

Illustrative estimate (assumed numbers, not a benchmark): assume 20 services (N), 6 build minutes each (M), 30 merges per day (R), and 3 affected services per merge on average (A).

Saved minutes per day = R × (N − A) × M = 30 × 17 × 6 = 3,060.

Subtract the scheduled full rebuild, which costs N × M = 120 minutes. That leaves about 2,940 runner minutes saved per day.

Those savings come with ongoing maintenance:

  • Graph accuracy: someone has to keep declared inputs and implicit dependencies correct as the repository changes.
  • Base-SHA state: the last-successful-commit reference can go stale or be reset, which makes CI compare against the wrong commit.
  • Manifest tooling: the deploy manifests that map services to tags need their own scripts and tests.

If R or N is small, that maintenance can cost more than the runner time it saves.

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