Dockerfile Best Practices for Smaller, Faster Images
A good Dockerfile builds fast and produces a small image. Learn layer caching, multi-stage builds, and the common mistakes.
By Velloreth
Layer caching
Each instruction in a Dockerfile creates a layer. Docker caches layers and reuses them when the instruction and its inputs are unchanged.
The rule: put the instructions that change least near the top.
# Good: dependencies cached separately from source
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "server.js"]
# Bad: any source change re-runs the install
FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm ci --omit=dev
CMD ["node", "server.js"]
In the bad version, editing a single source file invalidates the COPY . . layer and every layer after it, so the dependency install runs again. In the good version, the install is cached until package.json changes.
This is the single most impactful Dockerfile change.
Multi-stage builds
A multi-stage build uses one stage to build and another to run.
# Build stage
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Runtime stage
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]
The final image contains only the runtime dependencies and the built output. Build tools, dev dependencies, and intermediate files are left behind.
For a Go or Rust application, the difference is dramatic: a build stage with the full toolchain can be over a gigabyte, while the final image with just the binary is a few megabytes.
FROM golang:1.22 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /app
FROM scratch
COPY --from=build /app /app
ENTRYPOINT ["/app"]
FROM scratch is an empty image, so the result contains only the binary.
Combining RUN instructions
Each RUN is a layer. A cleanup in a later layer does not remove the files from the earlier one.
# Bad: the apt cache is still in the image
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*
# Good: install and clean in one layer
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
The --no-install-recommends flag avoids pulling in packages you did not ask for, which is a common source of bloat.
The .dockerignore
The build context is everything sent to the Docker daemon. A large context slows the build and can leak secrets.
node_modules
.git
.gitignore
dist
build
coverage
*.log
.env
.env.*
Dockerfile
compose.yaml
README.md
The node_modules exclusion is important: the container installs its own, and copying the host’s can break native modules built for a different platform.
Base images
Pin the version. A moving tag makes the build non-reproducible.
FROM node:20.11.1-alpine3.19 # pinned
FROM node:20-alpine # moving
FROM node:latest # worst
Prefer a slim or alpine base. node:20-alpine is around 130MB; node:20 is around 1GB.
The alpine caveat. Alpine uses musl libc rather than glibc. Native modules and prebuilt binaries compiled against glibc may not work. If you hit a compatibility problem, use a slim Debian image instead.
Use a distroless image for a minimal attack surface.
FROM gcr.io/distroless/nodejs20-debian12
Distroless images contain the runtime and nothing else: no shell, no package manager. This is more secure but harder to debug, because you cannot exec into a shell.
Running as non-root
By default, a container runs as root. A container escape then gives root on the host.
FROM node:20-alpine
WORKDIR /app
COPY --chown=node:node . .
USER node
CMD ["node", "server.js"]
The node user exists in the official Node images. For other bases, create one.
RUN addgroup -S app && adduser -S app -G app
USER app
Healthchecks
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node -e "fetch('http://localhost:3000/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
A healthcheck lets the orchestrator know whether the container is ready. Compose and Kubernetes both use it.
Signals and PID 1
The process with PID 1 in a container has special responsibilities: it must reap zombie processes and forward signals.
A shell-form CMD runs the command through /bin/sh, which does not forward signals properly.
# Bad: signals go to the shell, not the app
CMD node server.js
# Good: exec form, the app is PID 1
CMD ["node", "server.js"]
If your application does not handle signals, use an init process.
ENTRYPOINT ["tini", "--"]
CMD ["node", "server.js"]
Or, in Compose:
init: true
Common mistakes
Copying the source before installing dependencies. Any source change invalidates the install layer, so the install runs on every build. Copy the manifest first.
Cleaning up in a later layer. The files are still in the earlier layer, just hidden. Clean up in the same RUN.
A missing .dockerignore. The build context includes node_modules and .git, which slows the build and can leak secrets.
Running as root. A container escape gives root on the host. Create a user and switch to it.
The shell form of CMD. Signals go to the shell rather than the application, so a graceful shutdown does not happen. Use the exec form.
A moving base tag. node:latest makes the build non-reproducible and can break without a code change. Pin the version.
Secrets in a layer. A COPY . . that includes a .env bakes the secrets into the image, where they remain even if a later layer deletes the file. Use a .dockerignore, and pass secrets at runtime.
No healthcheck. The orchestrator cannot tell whether the container is ready, so it may route traffic to a container that is still starting.
Debugging a build
See the build output for a specific stage:
docker build --target build -t myapp:build .
docker run -it myapp:build sh
Building to an intermediate stage and running a shell in it is the fastest way to inspect what a stage produced.
See the layers:
docker history myapp
docker image inspect myapp
docker history shows the size of each layer, which immediately reveals which instruction is responsible for a large image.
Build without the cache:
docker build --no-cache -t myapp .
Useful when a cached layer is stale, though it is slow.
See the build context size:
docker build -t myapp . 2>&1 | head -5
The first line reports the context size. A context of hundreds of megabytes means the .dockerignore is missing or incomplete.
Practical guidance
- Copy the dependency manifest first, then install, then copy the source.
- Use a multi-stage build.
- Combine RUN instructions and clean up in the same layer.
- Add a
.dockerignore. - Pin the base image version.
- Run as a non-root user.
- Use the exec form of CMD.
- Add a healthcheck.
- Prefer a slim base unless you need the full toolchain.
For the related guides, see docker-basics-guide and docker-compose-guide. For the broader context, kubernetes-basics and ci-cd-pipeline-basics.
Quotable summary
Layer order determines cache reuse, so put the instructions that change least near the top, which means copying the dependency manifest and installing before copying the source. A multi-stage build keeps build tools out of the final image, which can cut the size by 80 percent or more. Combine related RUN instructions and clean up in the same layer, because a later cleanup does not shrink an earlier layer — the files are still in the image, just hidden. Use a .dockerignore to exclude node_modules, .git, and secrets from the build context, and pin base image versions so a build is reproducible. Run as a non-root user and use the exec form of CMD so signals reach the application.