Container Foundations · 8 min read · Intermediate
Writing Clean Dockerfiles & Layer Caching
Build fast, small Docker images using FROM, WORKDIR, COPY, RUN, CMD, and smart dependency layer ordering.
What you'll learn
- Order Dockerfile instructions so dependency installs are cached across code edits
- Exclude node_modules, .git, and .env using .dockerignore
- Prefer exec-form CMD ["node", "server.js"] for clean signal handling
Every RUN, COPY, and ADD instruction creates a cached layer. If you copy package.json and run npm ci before copying src/, Docker reuses the cached dependency layer whenever you edit source code, turning 60-second builds into 2-second builds.
Fill-in-the-Blank Exercise
Cache-Friendly Dockerfile
Set the working directory to /app and copy package files before installing.
FROM node:20-alpine
/app
package*.json ./
RUN npm ci
COPY . .
CMD ["node", "server.js"]Live Dockerfile Validation Lab
Bashdockerfile_check.sh
Expected OutputClick “Run Live” to compile with GNU Bash
FROM node:20-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --omit=dev COPY . . CMD ["node", "server.js"]
Check Your Understanding
Score: 0 / 1
1. Why should COPY package*.json ./ and RUN npm ci appear BEFORE COPY . . in a Dockerfile?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.