Skip to content

Dockerfiles and builds, including multi-stage

A Dockerfile is the recipe for an image. Getting it to produce an image is easy; getting it to produce a small, reproducible, secure image that rebuilds in seconds takes a handful of deliberate choices. This page walks through those choices in order: the instructions, the build context, layer caching, multi-stage builds, build-time inputs and secrets, and the base-image and user settings that decide your security posture.

The running example is the invented OrdersPortal application: an ASP.NET Core API (Orders.Api) and a Vite front end. No Docker daemon was available while writing this page, so the Dockerfiles and docker build commands are not run here; they follow the Dockerfile reference and build guides on docs.docker.com and Microsoft’s .NET container documentation. To try them, run docker build from the project root with Docker Desktop or Docker Engine.

Topic What it answers
Dockerfile instructions What each common instruction does and which form to use.
Build context and dockerignore What gets sent to the builder and how to keep secrets and junk out.
Layer caching Why instruction order decides how fast rebuilds are.
Multi-stage builds How to keep compilers and dev dependencies out of the final image.
Build arguments and build secrets Parameterizing builds, and passing credentials without leaking them.
Base images and non-root users Choosing a base image and running without root.

A Dockerfile is a list of instructions executed top to bottom. The ones you use in almost every file:

  • FROM image:tag AS name starts a build stage from a base image. A Dockerfile can have several stages.
  • WORKDIR /app sets (and creates) the working directory for the following instructions.
  • COPY src dest copies files from the build context or, with --from=stage, from another stage. ADD can also fetch URLs and unpack archives; prefer COPY unless you need that.
  • RUN command runs a command at build time and records the file changes as a layer.
  • ENV KEY=value sets an environment variable for later build steps and for containers. ARG NAME=default declares a build-time variable that is not present at run time.
  • EXPOSE 8080 documents the port the application listens on. It does not publish anything; docker run -p does.
  • USER name sets the user for later instructions and for the container.
  • ENTRYPOINT and CMD define what the container runs. ENTRYPOINT is the executable; CMD provides default arguments (or the whole command if there is no entrypoint) and is easy to override at docker run.
  • HEALTHCHECK defines a command Docker uses to report the container as healthy or unhealthy; Compose can wait on it.

Use the exec form (a JSON array) for ENTRYPOINT and CMD: ENTRYPOINT ["dotnet", "Orders.Api.dll"]. The shell form (ENTRYPOINT dotnet Orders.Api.dll) wraps the command in /bin/sh -c, so the shell becomes PID 1 and the application never receives SIGTERM on docker stop.

Starting a Dockerfile with # syntax=docker/dockerfile:1 tells BuildKit to use the latest stable Dockerfile frontend, which keeps newer features such as RUN --mount available regardless of the Engine version.

Pitfalls:

  • apt-get update in its own RUN. The cached update layer goes stale while later installs change. Combine update and install in one RUN and clean the package lists in the same step.
  • Expecting EXPOSE to open ports. It is metadata. Publish ports at run time.

docker build . sends the build context (the directory . and everything in it) to the builder. Only files in the context can be copied with COPY. A large context slows every build, and a careless COPY . . can bake local secrets, .git history or node_modules built for another OS into the image.

A .dockerignore file at the root of the context excludes paths, using patterns similar to .gitignore:

.dockerignore
.git
**/bin
**/obj
**/node_modules
**/dist
.env
.env.*
*.log
Dockerfile*
compose*.yaml

Excluding bin and obj matters for .NET: copying a host build output into the image can mix platform-specific files with the container’s build. Excluding .env files keeps local credentials out of image layers, where anyone who pulls the image could read them.

Pitfalls:

  • Building from the repository root of a monorepo without a .dockerignore. Every build uploads the whole repository. Narrow the context or the ignore file.
  • Ignoring a file the build needs. The error is “file not found” at the COPY step; check the ignore patterns first.

Each instruction produces a layer, and BuildKit reuses a cached layer when the instruction and its inputs are unchanged. Once one step’s cache is invalidated, every later step reruns. So order instructions from least to most frequently changing: base image, system packages, dependency manifests, dependency restore, then source code.

For OrdersPortal’s API, copying only the project files before dotnet restore means the restore layer is reused for every commit that does not change package references:

COPY src/Orders.Api/Orders.Api.csproj src/Orders.Api/
RUN dotnet restore src/Orders.Api/Orders.Api.csproj
COPY src/ src/
RUN dotnet publish src/Orders.Api/Orders.Api.csproj -c Release -o /app/publish --no-restore

The same pattern applies to Node.js (COPY package.json package-lock.json ./ then RUN npm ci, then COPY . .). Cache mounts go further: RUN --mount=type=cache,target=/root/.npm npm ci keeps the package manager’s download cache between builds without putting it in a layer.

In CI, the local cache is usually empty, so export and import it: docker buildx build --cache-to type=registry,ref=... --cache-from type=registry,ref=..., or the GitHub Actions cache backend.

Pitfalls:

  • COPY . . before installing dependencies. Any source change invalidates the dependency layer and every build reinstalls everything.
  • Commands with changing output but unchanged text. RUN curl .../latest.tar.gz is cached forever. Pin versions in the command so a change invalidates the cache.

A multi-stage build uses several FROM instructions in one Dockerfile. Earlier stages contain the SDK, compilers and dev dependencies; the final stage starts from a small runtime image and copies in only the build output with COPY --from. Everything left behind in earlier stages never reaches the shipped image. For .NET, the SDK image is several times the size of the ASP.NET Core runtime image, and for Node.js the TypeScript compiler and dev dependencies are left behind.

# syntax=docker/dockerfile:1
# Dockerfile for OrdersPortal's API (.NET 10)
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY src/Orders.Api/Orders.Api.csproj src/Orders.Api/
RUN dotnet restore src/Orders.Api/Orders.Api.csproj
COPY src/ src/
RUN dotnet publish src/Orders.Api/Orders.Api.csproj -c Release -o /app/publish --no-restore
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime
WORKDIR /app
COPY --from=build /app/publish .
USER $APP_UID
EXPOSE 8080
ENTRYPOINT ["dotnet", "Orders.Api.dll"]

ASP.NET Core images listen on port 8080 by default since .NET 8 and include a non-root app user whose UID is in the APP_UID environment variable, so this image runs without root and without changing the port.

A front end needs Node.js only to build; the final image can be a web server serving static files:

# syntax=docker/dockerfile:1
FROM node:24-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
FROM nginx:alpine AS runtime
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80

For a statically linked binary, such as a Go program built with CGO_ENABLED=0, the final stage can be gcr.io/distroless/static:nonroot or even scratch: no shell, no package manager, and very little for a scanner to report.

Named stages also serve other purposes. docker build --target build . stops at the SDK stage, which Compose can use for a development container with dotnet watch, and a CI pipeline can add a test stage that runs unit tests in the same environment as the build. BuildKit builds only the stages the target depends on, and builds independent stages in parallel.

Pitfalls:

  • Copying the whole build stage. COPY --from=build /src /app drags sources and intermediate files into the final image. Copy only the publish output.
  • A runtime stage that needs build tools. Native modules compiled in an Alpine (musl) build stage will not run on a Debian (glibc) runtime image. Use the same distribution family in both stages.

ARG declares a value passed at build time with --build-arg. It is useful for versions and feature flags of the build itself:

ARG DOTNET_VERSION=10.0
FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS build
ARG APP_VERSION=0.0.0-local
RUN echo "Building OrdersPortal API ${APP_VERSION}"
Terminal window
# Not run here
docker build --build-arg APP_VERSION=2.4.1 -t orders-api:2.4.1 .

An ARG declared before the first FROM is visible only to FROM lines; redeclare it inside a stage to use it there. To make a build value available at run time, copy it into an ENV.

Never pass credentials as ARG or ENV: their values can be recovered from the image’s history and metadata. When a build needs a credential, for example a token for a private NuGet or npm feed, use a secret mount. BuildKit mounts the secret as a file (by default at /run/secrets/<id>) or exposes it as an environment variable for one RUN instruction only, and it is not stored in any layer:

RUN --mount=type=secret,id=nuget_token,env=NUGET_TOKEN \
dotnet restore src/Orders.Api/Orders.Api.csproj
Terminal window
# Not run here: the value comes from the NUGET_TOKEN variable in your shell or CI
docker build --secret id=nuget_token,env=NUGET_TOKEN -t orders-api:dev .

For SSH-based Git dependencies, RUN --mount=type=ssh forwards your SSH agent in the same way.

Pitfalls:

  • COPY .npmrc with a token, then RUN rm .npmrc. The file still exists in the earlier layer. Use a secret mount.
  • Cache-busting by accident. Changing an ARG value invalidates the cache from the first instruction that uses it; declare build arguments as late as possible.

The base image decides most of your image size and most of your vulnerability count. Prefer official or vendor images (Docker Official Images, Microsoft’s mcr.microsoft.com/dotnet/*), pin a specific version tag or digest, and rebuild regularly so you pick up base-image security fixes. Smaller variants (Alpine, Debian slim, Microsoft’s chiseled Ubuntu images, distroless) reduce the attack surface, at the cost of fewer debugging tools in the container.

Run as a non-root user. If the process is compromised, root inside the container makes escaping or damaging the host easier, and Kubernetes clusters with Pod Security restrictions reject root containers outright. Use the user the base image provides (app in .NET images, node in the Node.js images, nonroot in distroless) or create one, and set USER before ENTRYPOINT. Non-root processes cannot bind ports below 1024 by default, which is one reason .NET images moved to 8080.

Finally, scan images in CI (docker scout cves or another scanner) and fail the build on critical findings that have a fix available.

Pitfalls:

  • FROM node:latest or untagged bases. Builds change under you. Pin the version.
  • Making files writable by the app user “just in case”. Keep the application read-only and give it a specific writable volume if it needs one.
Goal Technique
Fast rebuilds Order instructions by change frequency; cache mounts; registry cache in CI
Small runtime image Multi-stage build with a slim, chiseled or distroless final stage
Reproducible builds Pinned base image versions or digests; lock files; npm ci
No secrets in images .dockerignore for local files; secret mounts for build credentials
Safer containers Non-root USER, minimal base, regular rebuilds and scanning

What is the difference between CMD and ENTRYPOINT? ENTRYPOINT sets the executable the container runs; CMD sets default arguments, or the whole command when there is no entrypoint. Arguments after the image name in docker run replace CMD, while replacing ENTRYPOINT needs --entrypoint.

Why does instruction order matter in a Dockerfile? Each instruction is a cached layer, and a change invalidates the cache for every later instruction. Putting rarely changing steps (base image, dependency restore) before frequently changing ones (source copy, compile) lets most builds reuse the expensive layers.

How does a multi-stage build reduce image size? Only the final stage becomes the image. Compilers, SDKs and dev dependencies live in earlier stages, and the final stage copies just the build output onto a small runtime base.

Why is ARG the wrong way to pass a registry token to a build? Build arguments are recorded in the image history and metadata, so anyone with the image can read the token. A secret mount exposes the value to one RUN step without writing it to a layer.

Senior scenario: OrdersPortal’s image is 1.6 GB, builds take 12 minutes in CI and the scanner reports 300 vulnerabilities. Where do you start? Measure first with docker history and the build log. Convert to a multi-stage build so the runtime image is the ASP.NET Core runtime (or a chiseled variant) with only the publish output, which removes the SDK and most of the vulnerabilities. Reorder steps so restore is cached, add a .dockerignore, and enable a registry or CI cache backend so CI builds are warm. Pin and regularly refresh the base image, run as the app user, and gate merges on scanner findings that have fixes.