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.
Topics on this page
Section titled “Topics on this page”| 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. |
Dockerfile instructions
Section titled “Dockerfile instructions”A Dockerfile is a list of instructions executed top to bottom. The ones you use in almost every file:
FROM image:tag AS namestarts a build stage from a base image. A Dockerfile can have several stages.WORKDIR /appsets (and creates) the working directory for the following instructions.COPY src destcopies files from the build context or, with--from=stage, from another stage.ADDcan also fetch URLs and unpack archives; preferCOPYunless you need that.RUN commandruns a command at build time and records the file changes as a layer.ENV KEY=valuesets an environment variable for later build steps and for containers.ARG NAME=defaultdeclares a build-time variable that is not present at run time.EXPOSE 8080documents the port the application listens on. It does not publish anything;docker run -pdoes.USER namesets the user for later instructions and for the container.ENTRYPOINTandCMDdefine what the container runs.ENTRYPOINTis the executable;CMDprovides default arguments (or the whole command if there is no entrypoint) and is easy to override atdocker run.HEALTHCHECKdefines 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 updatein its ownRUN. The cached update layer goes stale while later installs change. Combine update and install in oneRUNand clean the package lists in the same step.- Expecting
EXPOSEto open ports. It is metadata. Publish ports at run time.
Build context and dockerignore
Section titled “Build context and dockerignore”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:
.git**/bin**/obj**/node_modules**/dist.env.env.**.logDockerfile*compose*.yamlExcluding 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
COPYstep; check the ignore patterns first.
Layer caching
Section titled “Layer caching”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.csprojCOPY src/ src/RUN dotnet publish src/Orders.Api/Orders.Api.csproj -c Release -o /app/publish --no-restoreThe 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.gzis cached forever. Pin versions in the command so a change invalidates the cache.
Multi-stage builds
Section titled “Multi-stage builds”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 buildWORKDIR /srcCOPY src/Orders.Api/Orders.Api.csproj src/Orders.Api/RUN dotnet restore src/Orders.Api/Orders.Api.csprojCOPY 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 runtimeWORKDIR /appCOPY --from=build /app/publish .USER $APP_UIDEXPOSE 8080ENTRYPOINT ["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:1FROM node:24-alpine AS buildWORKDIR /appCOPY package.json package-lock.json ./RUN --mount=type=cache,target=/root/.npm npm ciCOPY . .RUN npm run build
FROM nginx:alpine AS runtimeCOPY --from=build /app/dist /usr/share/nginx/htmlCOPY nginx.conf /etc/nginx/conf.d/default.confEXPOSE 80For 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 /appdrags 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.
Build arguments and build secrets
Section titled “Build arguments and build secrets”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.0FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS buildARG APP_VERSION=0.0.0-localRUN echo "Building OrdersPortal API ${APP_VERSION}"# Not run heredocker 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# Not run here: the value comes from the NUGET_TOKEN variable in your shell or CIdocker 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 .npmrcwith a token, thenRUN rm .npmrc. The file still exists in the earlier layer. Use a secret mount.- Cache-busting by accident. Changing an
ARGvalue invalidates the cache from the first instruction that uses it; declare build arguments as late as possible.
Base images and non-root users
Section titled “Base images and non-root users”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:latestor 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.
Choosing between them
Section titled “Choosing between them”| 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 |
Interview questions
Section titled “Interview questions”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.
Related pages
Section titled “Related pages”- Docker section start
- Docker images, containers and registries: what the build produces and where it goes.
- Docker Compose and environment variables: using build targets for development.
- Kubernetes workloads: running the image with probes and resource limits.