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
.dockerignorefile - Choose between full, slim, Alpine and distroless base images
- Use
CMDandENTRYPOINTcorrectly 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.
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:
- A
RUNis cached by its command text, not by what it downloads, soapt-get updatecan serve stale package lists from cache. - A
COPYorADDis invalidated when any copied file's content changes. - 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:
- Use a minimal base image.
- Use multi-stage builds so compilers and dev dependencies stay in the build stage.
- 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.
FROM node:24-alpineWORKDIR /appCOPY . .RUN npm ciRUN npm run buildCMD ["node", "dist/server.js"]# GOOD: dependencies are cached until package files changeFROM node:24-alpineWORKDIR /app # Dependency manifests onlyCOPY package.json package-lock.json ./RUN npm ci # Source code lastCOPY . .RUN npm run build CMD ["node", "dist/server.js"]See which steps hit the cache with plain progress output:
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:
RUN --mount=type=cache,target=/root/.npm npm ciStep 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.
# Dependencies are installed inside the imagenode_modulesnpm-debug.log # Build output is produced in the build stagedistbuild.nextcoverage # 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 runtimedocs*.md!README.mddocker 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:
docker pull node:24docker pull node:24-slimdocker pull node:24-alpinedocker image ls node # Scan an image for known vulnerabilitiestrivy image node:24-alpineTipCheck 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.
# Pattern 1: CMD only, common for applicationsCMD ["node", "dist/server.js"]# docker run IMAGE -> node dist/server.js# docker run IMAGE sh -> sh # Pattern 2: ENTRYPOINT plus CMD, common for toolsENTRYPOINT ["node"]CMD ["dist/server.js"]# docker run IMAGE other.js -> node other.jsA 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.
# syntax=docker/dockerfile:1 # ---- Production dependencies ----FROM node:24-alpine AS depsWORKDIR /appCOPY package.json package-lock.json ./RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev # ---- Build stage ----FROM node:24-alpine AS buildWORKDIR /appCOPY package.json package-lock.json ./RUN --mount=type=cache,target=/root/.npm npm ciCOPY . .RUN npm run build # ---- Final stage ----FROM node:24-alpine AS productionWORKDIR /app ENV NODE_ENV=productionENV PORT=8080 # tini handles signals and zombie processesRUN apk add --no-cache tini # The official node image already includes a non-root user called nodeCOPY --from=deps --chown=node:node /app/node_modules ./node_modulesCOPY --from=build --chown=node:node /app/dist ./distCOPY --chown=node:node package.json ./ USER nodeEXPOSE 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.
docker build -t payment-api:3.1.0 .docker image ls payment-apidocker history payment-api:3.1.0docker run --rm -p 8080:8080 payment-api:3.1.0prod 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.
RUN --mount=type=secret,id=npm_token \ NPM_TOKEN=$(cat /run/secrets/npm_token) npm cidocker 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.
SecurityA 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.
# 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.0Production 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
USERafter installing everything that needs root. - Use exec form for
CMDandENTRYPOINT. Combine it withtinior--initfor clean shutdowns. - Clean package caches in the same
RUN. For Debian-based images useapt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*, since a laterRUNcannot shrink an earlier layer. - Prefer
COPYoverADD. UseADDonly for deliberate tar extraction. - Treat
EXPOSEas documentation. It does not publish a port. You still need-por a Composeportsentry. - Use OCI labels. The
MAINTAINERinstruction is deprecated, andorg.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 |