Loading
Portfolio
Rayden Li
Docker
This guide builds a production Docker image for a Node.js/Next.js application, then explains every Dockerfile instruction. The same principles—small build contexts, stable cache layers, multi-stage builds, and a minimal runtime—apply to other stacks too.
Example runtime: Node.js 22 on Debian Bookworm Slim. It is a deliberate, major-version example, not a claim that Node.js 22 is the newest release. Choose a Node.js release supported by your application and organization.
A Dockerfile affects several different kinds of performance:
| Goal | What improves it |
|---|---|
| Faster builds | Good cache ordering, a small build context, cache mounts, and a reusable CI cache |
| Smaller image | Multi-stage builds and copying only production artifacts |
| Faster deployment or cold start | Fewer bytes to pull and unpack; this is workload- and platform-dependent |
| Runtime throughput | Mostly application code, Node.js behavior, CPU, memory, and downstream services—not image size alone |
| Security and operability | A non-root user, current base images, no embedded secrets, direct signal delivery, and health checks |
A smaller image does not automatically make JavaScript execute faster. It primarily reduces storage, transfer, and unpacking work. Docker recommends multi-stage builds to keep build tools out of the runtime image, reducing image size and attack surface (Docker: multi-stage builds).
The example assumes:
package-lock.json.build in package.json, usually next build..dockerignore file beside the Dockerfile.npm ci is intended for automated, clean installs. It requires a lockfile, fails when the lockfile and package.json disagree, and does not rewrite either file (npm: npm ci).
Create or update next.config.js:
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
}
module.exports = nextConfig
Line by line:
const nextConfig = { begins the Next.js configuration object.output: 'standalone' tells Next.js to trace runtime dependencies and create .next/standalone.} closes the object.module.exports = nextConfig exports it for Next.js.Standalone output includes a minimal server.js and the traced runtime files, including only the required parts of node_modules. It does not automatically copy public or .next/static, so the Dockerfile copies those directories explicitly (Next.js: standalone output).
Create .dockerignore in the project root:
.git
.next
node_modules
coverage
npm-debug.log*
.env*
!.env.example
.npmrc
Dockerfile*
.dockerignore
Every line has a purpose:
| Line | Why it is excluded |
|---|---|
.git | Git history is unnecessary in the image and can make the context much larger. |
.next | Never send a host build into a clean container build. |
node_modules | Dependencies must be installed for the container OS and CPU, not copied from the host. |
coverage | Test reports are not production runtime files. |
npm-debug.log* | Local npm logs are not needed in the image. |
.env* | Prevents local environment files and possible secrets from entering the build context. |
!.env.example | Re-includes a safe example file if the project uses one. Later matching rules take precedence. |
.npmrc | Prevents a local registry token from being copied accidentally. Use a BuildKit secret for private packages. |
Dockerfile* | Docker still reads the selected Dockerfile, but COPY . . cannot add it to the image. |
Docker removes ignored paths before sending the context to the builder. This makes transfers faster—especially with a remote builder—and prevents ignored files from invalidating COPY layers (Docker: build context and .dockerignore).
Do not blindly ignore files your build actually consumes. For example, do not add *.md if the application imports Markdown content.
Create Dockerfile in the project root:
# syntax=docker/dockerfile:1
ARG NODE_VERSION=22-bookworm-slim
FROM node:${NODE_VERSION} AS base
WORKDIR /app
FROM base AS deps
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci --no-audit --no-fund
FROM base AS builder
ENV NEXT_TELEMETRY_DISABLED=1
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN --mount=type=cache,target=/app/.next/cache \
mkdir -p public && npm run build
FROM base AS runner
ENV NODE_ENV=production \
NEXT_TELEMETRY_DISABLED=1 \
PORT=3000 \
HOSTNAME=0.0.0.0
RUN mkdir .next && chown node:node .next
COPY --from=builder --chown=node:node /app/public ./public
COPY --from=builder --chown=node:node /app/.next/standalone ./
COPY --from=builder --chown=node:node /app/.next/static ./.next/static
USER node
EXPOSE 3000
CMD ["node", "server.js"]
The backslash (\) at the end of a line only continues the same Dockerfile instruction onto the next line.
| Instruction | Explanation and performance effect |
|---|---|
# syntax=docker/dockerfile:1 | Selects the current stable Dockerfile frontend syntax. It enables features used below, including RUN --mount. This is a parser directive, not an image layer. |
ARG NODE_VERSION=22-bookworm-slim | Defines the build-time base-image tag. 22 constrains the Node.js major, bookworm fixes the Debian family, and slim removes many common OS packages. Override it with --build-arg NODE_VERSION=.... |
FROM node:${NODE_VERSION} AS base | Starts a shared stage from the official Node.js image and names it base. Later stages inherit this exact environment. The Node image documentation says Debian variants use supported Node.js platforms; it also describes Slim as containing only the minimal packages needed to run Node.js (official Node.js Docker image). |
WORKDIR /app | Sets /app as the working directory for following RUN, COPY, and CMD instructions. Docker creates it if necessary; absolute paths are clearer and safer (Dockerfile ). |
Docker processes instructions in order. When a layer changes, the following layers must also rebuild. Copying the whole repository before npm ci would make every source edit invalidate the expensive dependency install. The example creates this dependency chain instead:
package files change -> npm ci reruns -> application rebuilds
source files change -> npm ci stays cached -> application rebuilds
nothing changes -> both steps can stay cached
BuildKit cache mounts add another level. If a lockfile change forces npm ci to run, npm can still reuse already downloaded packages from /root/.npm. Docker documents cache mounts as cumulative build caches whose contents are not copied into the final image (Docker: cache mounts).
The .next/cache mount has one tradeoff: files written inside that mounted directory are not committed to the builder layer. This example does not copy .next/cache into the runtime image. If your deployment intentionally relies on a build-generated Next.js fetch cache at runtime, remove that mount and explicitly copy the required cache after confirming its ownership and lifecycle. The official Next.js Docker example calls out the same tradeoff (Next.js Dockerfile example).
Modern Docker uses BuildKit, but an older or restricted builder may reject RUN --mount. Replace the two mounted instructions with:
RUN npm ci --no-audit --no-fund
# In the builder stage
RUN mkdir -p public && npm run build
Layer caching still works; only the persistent package-manager and compiler caches are lost.
If the deployment platform honors image-level Docker health checks, add this before CMD and change / to a cheap, dependency-free health endpoint:
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD ["node", "-e", "fetch('http://127.0.0.1:3000/').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]
--interval=30s checks every 30 seconds.--timeout=3s fails an individual check after three seconds.--start-period=10s allows startup time before failures count.--retries=3 requires three consecutive failures before the container is unhealthy.CMD [...] runs Node directly and exits with status 0 only for a successful HTTP response.This uses Node’s built-in fetch, so it does not install curl solely for health checking. Do not add both this check and an equivalent orchestrator probe unless you deliberately want both; repeated probes consume a small amount of CPU and request capacity. See the HEALTHCHECK reference for its runtime behavior.
From the directory containing the Dockerfile:
docker build --pull --progress=plain -t nextjs-app:local .
docker run --rm --name nextjs-app -p 3000:3000 nextjs-app:local
Open http://localhost:3000. The -p 3000:3000 option maps host port 3000 to the documented container port.
Run the build a second time to see cached steps:
docker build --progress=plain -t nextjs-app:local .
Then change only an application source file and build again. The npm ci instruction should remain cached.
Use these commands before and after a Dockerfile change:
# Compare elapsed build time and inspect CACHED steps.
time docker build --progress=plain -t nextjs-app:test .
# Show the final image's reported size.
docker image ls nextjs-app:test
# Show which instructions contribute to image history.
docker history nextjs-app:test
# Observe container CPU and memory while it handles realistic traffic.
docker stats nextjs-app
# Inspect known vulnerabilities when Docker Scout is available.
docker scout cves nextjs-app:test
Test both a cold build and a warm rebuild. Measure image pull time on the actual registry and runtime performance under representative traffic. An image-size improvement and an application-throughput improvement are different results.
For ephemeral CI builders, local cache mounts disappear with the builder. Docker supports exporting and importing cache with docker buildx build --cache-to and --cache-from (Docker: external build cache).
Docker warns that ARG and ENV are inappropriate for secrets because their values can persist in image metadata or layers. Use a secret mount instead (Docker: build secrets). For a private npm registry, change the dependency instruction to:
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
--mount=type=cache,target=/root/.npm \
npm ci --no-audit --no-fund
Build with:
docker build --secret id=npmrc,src=.npmrc -t nextjs-app:local .
The secret exists only for that RUN instruction and is not copied into the image.
node:alpine can be smaller, but Alpine uses musl libc rather than glibc. Native Node.js modules may need different binaries or compilation steps. The official Node.js image project currently classifies amd64 musl builds as experimental and says other musl architectures are not tested before release (Node.js Docker image: musl builds).
Use Alpine only after testing every native dependency on every production architecture. Debian Slim is a practical compatibility-first default. If the Slim image lacks a system library your application needs, install only that library and clean package lists in the same RUN instruction, following Docker’s apt-get guidance.
COPY . .
RUN npm ci
Any source edit invalidates COPY, so Docker must run npm ci again. Copy the manifests first.
A single-stage image often contains source files, development dependencies, compiler caches, and build tools. Use a final runtime stage and copy only the standalone output.
npm ci --omit=dev can remove TypeScript, linters, CSS tools, and bundler plugins needed by next build. Install the complete locked tree in the build stage; standalone output prevents that complete tree from entering the final stage.
latest tagAn unbounded tag can change the Node.js major or OS unexpectedly. This example fixes the major and distribution with node:22-bookworm-slim. For strict reproducibility, pin the base image by digest and use an automated update process; Docker explains the security/reproducibility tradeoff in its base image pinning guidance.
ARG, ENV, or COPYThose mechanisms are not secret storage. Keep secret files out of the context and mount them for only the instruction that needs them.
The build may run as root, but the final server generally does not need to. Set ownership during COPY, prepare writable directories, and switch to USER node before CMD.
EXPOSE publishes a portIt documents intent only. Use docker run -p, Compose ports, or the deployment platform’s port configuration.
Do not replace a compatible base with a smaller one without testing native modules, TLS certificates, time zones, fonts, image libraries, and all target CPU architectures. Also benchmark the actual application: Dockerfile changes rarely repair slow database queries or excessive server-side rendering work.
.dockerignore small, explicit, and reviewed.npm ci.ARG, ENV, or ordinary COPY.CMD for direct signal delivery..dockerignore| Docker still reads this file, but the application does not need it. |
WORKDIRFROM base AS deps | Begins the dependency-installation stage. Naming the stage lets later stages copy from it without shipping all of its layers in the final image. |
COPY package.json package-lock.json ./ | Copies only dependency manifests first. Ordinary source changes therefore do not invalidate the dependency-install layer; changing a dependency correctly does. Docker recommends ordering layers from less frequently changed to more frequently changed (Docker: optimize build cache). |
RUN --mount=type=cache,target=/root/.npm \ | Gives npm a persistent BuildKit download cache. The mount speeds later installs but is not stored in the final image. |
npm ci --no-audit --no-fund | Installs the exact lockfile dependency tree. --no-audit and --no-fund remove network/reporting work from this build step; run security scanning separately in CI rather than silently skipping it everywhere. |
FROM base AS builder | Begins a clean build stage. It inherits Node.js and /app, but not the filesystem changes from deps unless they are copied explicitly. |
ENV NEXT_TELEMETRY_DISABLED=1 | Disables Next.js telemetry during the image build. Environment values do not automatically carry into a later, unrelated stage, so it is set again in runner. |
COPY --from=deps /app/node_modules ./node_modules | Reuses the dependency tree produced by the deps stage instead of reinstalling it. Development dependencies remain available to compilers and bundlers here. |
COPY . . | Copies the remaining filtered source context. It appears after dependency installation so normal source edits invalidate the build step, not npm ci. |
RUN --mount=type=cache,target=/app/.next/cache \ | Persists the Next.js compiler cache between builds. This can speed incremental rebuilds. Cache-mount contents do not become image contents. |
mkdir -p public && npm run build | Ensures public exists so the later COPY works even when the project has no public assets, then builds the application. && prevents the build from running if directory creation fails. |
FROM base AS runner | Starts the final runtime stage. Build caches, source-only files, and the complete build dependency tree are not automatically included. Only subsequent copies enter the production image. |
ENV NODE_ENV=production \ | Selects production behavior in Node.js libraries. The following continued lines belong to the same ENV instruction. |
NEXT_TELEMETRY_DISABLED=1 \ | Disables Next.js telemetry at runtime as well as during the build. |
PORT=3000 \ | Tells the standalone Next.js server which port to listen on. |
HOSTNAME=0.0.0.0 | Listens on all container network interfaces rather than only loopback. Next.js documents both PORT and HOSTNAME for standalone server.js. |
RUN mkdir .next && chown node:node .next | Creates a runtime-writable .next directory and gives it to the existing node user. This supports runtime cache files without running the whole container as root. |
COPY --from=builder --chown=node:node /app/public ./public | Copies public assets from the build stage and gives them to the runtime user. |
COPY --from=builder --chown=node:node /app/.next/standalone ./ | Copies the minimal standalone server and traced runtime dependencies, instead of the complete source tree and all build dependencies. |
COPY --from=builder --chown=node:node /app/.next/static ./.next/static | Adds browser bundles and other static Next.js output that standalone mode intentionally does not copy by itself. |
USER node | Makes the remaining instructions and the running process use the non-root node account provided by the official image. This limits the effect of a process compromise (Dockerfile USER). |
EXPOSE 3000 | Documents the container’s intended TCP port. It does not publish the port; docker run -p does that (Dockerfile EXPOSE). |
CMD ["node", "server.js"] | Defines the default process in JSON/exec form. Node runs directly rather than behind /bin/sh, so it receives stop signals directly. Runtime arguments supplied to docker run can replace this default (Dockerfile CMD). |