Skip to main content

Writing Production-Grade Dockerfiles

Write small, secure, cache-friendly Dockerfiles using layer ordering, .dockerignore, multi-stage builds, minimal base images and non-root users.

44 Terms

Overview and What You Will Learn

A production-grade Dockerfile builds quickly because it orders instructions to reuse cached layers, produces a small image with a minimal base, and runs the application as a non-root user. The biggest wins come from three habits: copy dependency files before source code, exclude junk with .dockerignore, and use a multi-stage build so build tools never reach the final image.

By the end of this lab you will be able to:

  • Explain how layers and the build cache work, and what invalidates them
  • Order instructions so code-only changes rebuild in seconds
  • Write a correct .dockerignore file
  • Choose between full, slim, Alpine and distroless base images
  • Use CMD and ENTRYPOINT correctly with exec form
  • Build a multi-stage image that runs as a non-root user with a health check
  • Keep secrets out of image layers

Why This Matters in Production

Slow builds and large images cost time on every commit and every deployment. A build that takes 8 minutes instead of 1 minute wastes 7 minutes of waiting per run, and an image that is 1.5 GB larger takes longer to pull on every node that deploys it.

As an illustration, a team with 40 services building on every push, each wasting 7 minutes to a badly ordered Dockerfile, loses nearly five hours of pipeline time per push cycle. Large images also carry more packages, which means more known vulnerabilities to patch and a larger attack surface. These numbers are an example, not a measurement from a specific company.

Core Principles

How Layers and the Build Cache Work

Instructions that change the filesystem (RUN, COPY, ADD) create layers, while the others add metadata. Docker reuses a cached layer when the instruction and its inputs are unchanged, and once one layer misses the cache, every layer after it is rebuilt.

flowchart TD A["FROM base image"] --> B["COPY package files"] B --> C["RUN npm ci"] C --> D["COPY source code"] D --> E["RUN npm run build"] classDef hit fill:#D1FAE5,color:#1E293B classDef miss fill:#FFEDD5,color:#1E293B class A,B,C hit class D,E miss

In this ordering, a source-only change misses the cache at COPY source code (orange) while the slow dependency install above it stays cached (green). Put COPY . . before npm ci and every code change reinstalls all dependencies.

Cache rules to remember:

  1. A RUN is cached by its command text, not by what it downloads, so apt-get update can serve stale package lists from cache.
  2. A COPY or ADD is invalidated when any copied file's content changes.
  3. A miss invalidates every later layer.
What Makes an Image Small and Safe

Small images pull faster and carry fewer vulnerabilities. Three techniques deliver most of the benefit:

  1. Use a minimal base image.
  2. Use multi-stage builds so compilers and dev dependencies stay in the build stage.
  3. Exclude files you never need with .dockerignore.

Detailed Step-by-Step Practical Lab

Step 1 - How to Order Instructions for Maximum Cache Reuse

Copy only the dependency manifests, install, and then copy the rest of the source. Comments must be on their own line, because Dockerfiles do not support trailing comments.

Dockerfile
FROM node:24-alpine
WORKDIR /app
COPY . .
RUN npm ci
RUN npm run build
CMD ["node", "dist/server.js"]
Dockerfile
# GOOD: dependencies are cached until package files change
FROM node:24-alpine
WORKDIR /app
# Dependency manifests only
COPY package.json package-lock.json ./
RUN npm ci
# Source code last
COPY . .
RUN npm run build
CMD ["node", "dist/server.js"]

See which steps hit the cache with plain progress output:

Bash
docker build --progress=plain -t payment-api:dev .
# #5 [3/6] COPY package.json package-lock.json ./
# #5 CACHED
# #6 [4/6] RUN npm ci
# #6 CACHED
# #7 [5/6] COPY . .
# (rebuilt because source changed)

For faster installs even when the cache misses, mount the package manager cache with BuildKit:

Dockerfile
RUN --mount=type=cache,target=/root/.npm npm ci
Step 2 - How to Write a .dockerignore File

.dockerignore stops files from being sent to the Docker daemon as build context, which speeds up builds and keeps secrets out of images. Each pattern must be on its own line, because a # after a pattern is treated as part of the pattern, not a comment.

Bash
# Dependencies are installed inside the image
node_modules
npm-debug.log
# Build output is produced in the build stage
dist
build
.next
coverage
# Version control and editor files
.git
.gitignore
.vscode
.idea
.DS_Store
# Environment files and secrets
.env
.env.*
!.env.example
# Docs and tests not needed at runtime
docs
*.md
!README.md
Bash
docker build -t payment-api:dev .
# [internal] load build context
# transferring context: 2.3MB (was hundreds of MB without .dockerignore)
Step 3 - How to Choose a Base Image

Pick the smallest base that your application actually runs on, and pin it to a specific version. Moving tags such as latest or a bare node:alpine change under you and make builds irreproducible.

Base Image Best For
node:24 (full Debian) Build stages that need compilers and tools
node:24-slim Runtime images that need glibc without extras
node:24-alpine Small runtime images, if dependencies work with musl libc
Distroless Node image Runtime with no shell or package manager, smallest attack surface

Compare sizes and vulnerabilities for your own app instead of trusting fixed numbers:

Bash
docker pull node:24
docker pull node:24-slim
docker pull node:24-alpine
docker image ls node
# Scan an image for known vulnerabilities
trivy image node:24-alpine
Tip

Check the current Node.js LTS release before you copy a tag, because older lines reach end of life. For stricter reproducibility, pin by digest, for example node:24-alpine@sha256:<digest>.

Step 4 - How to Use CMD and ENTRYPOINT Correctly

ENTRYPOINT sets the fixed executable and CMD sets default arguments that docker run can replace. Always use exec form (a JSON array), because shell form wraps your command in /bin/sh -c, which can swallow signals.

Dockerfile
# Pattern 1: CMD only, common for applications
CMD ["node", "dist/server.js"]
# docker run IMAGE -> node dist/server.js
# docker run IMAGE sh -> sh
# Pattern 2: ENTRYPOINT plus CMD, common for tools
ENTRYPOINT ["node"]
CMD ["dist/server.js"]
# docker run IMAGE other.js -> node other.js

A process running as PID 1 gets no default signal behavior from the kernel, so it must handle SIGTERM itself or ignore it. Either add a signal handler in your code, or run a tiny init process such as tini (docker run --init also does this) so shutdowns are clean and zombie processes are reaped.

Step 5 - How to Build a Multi-Stage Production Image

A multi-stage build uses one stage to build the app and a clean final stage that receives only what it needs to run. This final image has production dependencies, compiled output, a non-root user and a health check.

Dockerfile
# syntax=docker/dockerfile:1
# ---- Production dependencies ----
FROM node:24-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev
# ---- Build stage ----
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
# ---- Final stage ----
FROM node:24-alpine AS production
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=8080
# tini handles signals and zombie processes
RUN apk add --no-cache tini
# The official node image already includes a non-root user called node
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --chown=node:node package.json ./
USER node
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["node", "dist/server.js"]
LABEL org.opencontainers.image.title="payment-api"
LABEL org.opencontainers.image.version="3.1.0"
LABEL org.opencontainers.image.source="https://github.com/razorpay/payment-api"

Using COPY --chown sets ownership while copying. Running a separate RUN chown -R afterwards would duplicate every file in a new layer and make the image larger.

Bash
docker build -t payment-api:3.1.0 .
docker image ls payment-api
docker history payment-api:3.1.0
docker run --rm -p 8080:8080 payment-api:3.1.0
flowchart LR A["deps stage
prod node_modules"] --> D(["final image"]) B["build stage
compile to dist"] --> D C["base image
node alpine"] --> D classDef stage fill:#DBEAFE,color:#1E293B classDef out fill:#10B981,color:#FFFFFF classDef base fill:#F1F5F9,color:#1E293B class A,B stage class D out class C base
Step 6 - How to Keep Secrets Out of Image Layers

Anything written to an image layer can be read by anyone who can pull the image. ENV and ARG values show up in docker inspect or docker history, so never use them for secrets. Use a BuildKit secret mount, which is available only during one RUN step and is not saved in a layer.

Dockerfile
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN=$(cat /run/secrets/npm_token) npm ci
Bash
docker build --secret id=npm_token,src=$HOME/.npm-token -t payment-api:3.1.0 .

At runtime, pass secrets from a secret store such as AWS Secrets Manager into the container's environment or a mounted file, rather than baking them into the image.

Security

A secret that was copied into a layer and deleted in a later step is still stored in the earlier layer. Rebuild the image without it, and rotate the exposed secret.

Step 7 - How to Check an Image Before You Ship It

Verify size, user and layer contents before you push.

Bash
# Who does the container run as? It should not print root.
docker run --rm payment-api:3.1.0 id
# Which layers are biggest?
docker history --no-trunc payment-api:3.1.0
# Does the image have known vulnerabilities?
trivy image payment-api:3.1.0

Production Best Practices & Common Pitfalls

  • Order instructions from least to most frequently changing. Base image, system packages, dependency manifests, install, then source.
  • Pin base images. Use an exact tag, and a digest for the strictest reproducibility.
  • Run as non-root. Add USER after installing everything that needs root.
  • Use exec form for CMD and ENTRYPOINT. Combine it with tini or --init for clean shutdowns.
  • Clean package caches in the same RUN. For Debian-based images use apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*, since a later RUN cannot shrink an earlier layer.
  • Prefer COPY over ADD. Use ADD only for deliberate tar extraction.
  • Treat EXPOSE as documentation. It does not publish a port. You still need -p or a Compose ports entry.
  • Use OCI labels. The MAINTAINER instruction is deprecated, and org.opencontainers.image.* labels are the standard.
  • Rebuild regularly. Base images receive security patches, so rebuild and rescan on a schedule.

Quick Reference & Troubleshooting Commands

Command Description
docker build -t NAME:TAG . Build an image from the current directory
docker build --progress=plain . Show every step and cache hit
docker build --no-cache . Ignore the cache for one build
docker build --target build . Stop at a named stage
docker history IMAGE Show layers and their sizes
docker image ls List images and sizes
docker run --rm IMAGE id Check which user the container runs as
Problem Cause Fix
Dependencies reinstall on every build COPY . . before the install step Copy package files first, install, then copy source
Very large build context No .dockerignore Add one that excludes node_modules, .git and build output
Image over 1 GB Full base image or dev dependencies included Use slim or Alpine and a multi-stage build
Exit code 127 Command in CMD not found in the image Check the path and that the final stage has the binary
Exit code 126 File exists but is not executable Fix permissions or the shebang line
Container takes 10 seconds to stop SIGTERM is not handled Use exec form, add a signal handler or tini
Trailing comment breaks an instruction Dockerfile treats it as arguments Put comments on their own line

Resources

Explore More in Docker Images and Registry Management

All 4 Topics

Frequently Asked Questions

Is Writing Production-Grade Dockerfiles free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Writing Production-Grade Dockerfiles topic cover?

Write small, secure, cache-friendly Dockerfiles using layer ordering, .dockerignore, multi-stage builds, minimal base images and non-root users.

Found a mistake, an outdated step or a broken link?