All articles

Architecture

Your Docker image is mostly things you do not need

Two Dockerfiles from the same monorepo: a Next.js app and a Node API. They solve the same problem in different ways, and the difference explains what multi-stage builds are actually for. Plus the monorepo setting that breaks workspace resolution.

Jithin Roy, Full Stack Developer

By

Full Stack Developer, Kerala, India

7 min read

A naive Dockerfile copies the repository in, installs everything, builds, and runs. The resulting image contains your source code, your test files, your development dependencies, the compiler that produced the build, and the package manager's cache. To run a compiled application, you have shipped the entire workshop.

Multi-stage builds fix this, and every explanation of them stops at the general principle. What is more useful is two Dockerfiles from the same monorepo that reach the same goal by different routes, because the difference between them is the thing worth understanding.

Order the build so caching works

Before size, layers. Docker caches each instruction and invalidates everything after the first one whose inputs changed. Copy the whole repository before installing dependencies and every source edit re-runs the install, which is the single most common reason a build takes four minutes when it should take twenty seconds.

FROM base AS deps
WORKDIR /app
COPY package.json package-lock.json turbo.json ./
COPY apps/web/package.json ./apps/web/
COPY apps/admin/package.json ./apps/admin/
COPY apps/api/package.json ./apps/api/
COPY packages/types/package.json ./packages/types/
RUN npm ci
Only the manifests, then install. Editing a component does not invalidate this layer.

The detail specific to a monorepo: npm needs every workspace's package.json to resolve the tree, even when you are only building one app. So each is copied individually rather than copying the directories they live in, which would drag the source along and defeat the whole arrangement. It is verbose and it is the point.

Use npm ci rather than npm install. It installs exactly what the lockfile says, fails if the lockfile disagrees with the manifest, and does not silently update anything. A build that can quietly resolve a different dependency tree than your machine did is not reproducible.

The Next.js route: trace, do not prune

Next.js has a build mode that changes the shape of this problem entirely:

// next.config.mjs
output: "standalone",
outputFileTracingRoot: path.join(__dirname, "../../"),

Standalone output traces which files the application actually reaches at runtime and emits a self-contained directory containing only those, along with a server.js that runs it. The result needs no node_modules install in the final image, because the modules it genuinely uses have already been copied in, and the ones it does not have been left behind.

That turns the runner stage into three copies and a user:

FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs
COPY --from=builder /app/apps/web/public ./apps/web/public
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static
USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
CMD ["node", "apps/web/server.js"]

Three things there catch people out.

Static assets and public files are not traced, because nothing imports them. They have to be copied separately, and forgetting them produces an application that runs and serves unstyled pages, which is a confusing failure because the container looks healthy.

HOSTNAME must be set to 0.0.0.0. The default binds to localhost inside the container, which means nothing outside it can connect, and the symptom is a container that starts cleanly and refuses every connection.

And the entry point is apps/web/server.js, not server.js, because standalone output preserves the monorepo's directory structure inside the image. That path looks wrong every time I read it and is correct.

The monorepo setting that decides whether it works at all

This is the one that costs an afternoon.

File tracing starts from a root directory and follows imports. By default that root is the application's own directory. In a monorepo, the things you most need traced live above it: shared workspace packages, and the hoisted node_modules at the repository root.

outputFileTracingRoot: path.join(__dirname, "../../")

Without that line, the trace never walks up, the shared package is not copied, and the image builds successfully and crashes on start with a module not found error naming a package that plainly exists in your repository. The build gives no warning, because from its point of view nothing went wrong.

Point the tracing root at the repository root, not the app. The failure mode is a clean build and a crash at startup, which is the worst combination for debugging.

The builder stage then copies only the app and the workspace packages it needs, and builds through turbo with a filter, so building the web image does not compile the admin panel:

COPY apps/web ./apps/web
COPY packages/types ./packages/types
RUN npx turbo run build --filter=@synerggy/web

The Node API route: prune, because there is nothing to trace

The API in the same repository is a plain Node service compiled to a dist directory. There is no tracing, so the runner genuinely needs node_modules, and the question becomes which ones.

The answer is a fourth stage that exists only to produce a clean production dependency tree:

FROM base AS prod-deps
WORKDIR /app
COPY package.json package-lock.json ./
COPY apps/web/package.json ./apps/web/
COPY apps/admin/package.json ./apps/admin/
COPY apps/api/package.json ./apps/api/
COPY packages/types/package.json ./packages/types/
RUN npm ci --omit=dev --workspace @synerggy/api --include-workspace-root

This installs from scratch rather than deleting things from the deps stage, which matters: pruning an existing tree leaves behind whatever a package manager decided not to remove, while a fresh install with --omit=dev produces exactly the set you asked for. The build stage keeps its TypeScript compiler and its types; the runner never sees them.

The --include-workspace-root flag is the monorepo detail again. npm hoists shared dependencies to the root, so installing only the workspace gives you a tree missing everything hoisted, and the container fails at startup for the same reason as the tracing root problem. Hence two copies in the runner:

COPY --from=prod-deps /app/node_modules ./node_modules
COPY --from=prod-deps /app/apps/api/node_modules ./apps/api/node_modules
Hoisted dependencies live at the root; workspace-specific ones live beside the app. You need both.

Two smaller things. The base image adds openssl, because Prisma's query engine needs it and Alpine does not ship it, which produces a runtime error about a missing shared library that reads as a Prisma bug and is not. And the prisma directory is copied into the runner even though the client was generated at build time, because the schema is needed by the migration step in the entry command.

Alpine, libc6-compat, and the entry command

Both images start from Alpine, which is small because it uses musl rather than glibc. Native Node modules are frequently compiled against glibc, so:

FROM node:22-alpine AS base
RUN apk add --no-cache libc6-compat

That compatibility shim is a few hundred kilobytes and prevents a class of confusing native module failures. The --no-cache flag stops apk writing an index into the layer, which is the same instinct as everything else here: do not persist something you only needed during the build.

Both images also create and switch to a non-root user. Containers run as root by default, and a process that never needs to write outside its own directory should not have the ability to.

The API's entry command is worth one honest note:

CMD ["sh", "-c", "node dist/prestart.js && npx prisma db push && node dist/server.js"]

Running a schema migration on container start is convenient for a small deployment and genuinely risky at scale: start three replicas and three of them race to migrate the same database. For a single-container service it is fine and saves a deployment step. If this ever scales horizontally, that line has to move into a separate job that runs once. Better to write that down than to discover it during a scale-up.

What to take from this

  1. Copy manifests and install before copying source, so an edit does not invalidate the dependency layer.
  2. In a monorepo, copy every workspace package.json individually. npm needs them all to resolve, and copying directories drags source in.
  3. Use npm ci. A build that can resolve a different tree than your machine is not reproducible.
  4. For Next.js, use standalone output and copy public and .next/static separately. Nothing imports them, so nothing traces them.
  5. Set outputFileTracingRoot to the repository root, or workspace packages are silently omitted and the image crashes on start.
  6. Set HOSTNAME to 0.0.0.0, or the container starts and accepts nothing.
  7. For a plain Node service, add a stage that installs production dependencies fresh rather than pruning an existing tree.
  8. Use --include-workspace-root, and copy both node_modules directories.
  9. Add libc6-compat on Alpine, and openssl if you use Prisma.
  10. Run as a non-root user.
  11. Think twice about migrating on container start. It is fine for one replica and a race for several.

The two Dockerfiles reach the same place from opposite directions. Next.js works out what is needed and copies only that; the Node service installs only what is needed and copies all of it. Either way the question is the same one, asked at build time rather than left to the runtime: what does this actually need in order to run? Almost everything else in your image is the answer to a different question. The platform these deploy is written up in the Synerggy Events case study.