Build Context, Cache and Image Size
Overview
The build context is the local directory sent to Docker when you run docker build. Docker sends context files before evaluating Dockerfile instructions, so excluding unrelated files makes builds faster and can prevent secrets from entering the build.
Detailed Notes
.dockerignore
.git
node_modules
dist
coverage
.env
*.log
Docker sends the context but removes ignored paths before build instructions run. Never rely on .dockerignore alone to protect secrets that may already exist in source control.
Cache-friendly Dockerfile
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
If only src/app.js changes, Docker reuses the base image, dependency files and npm ci layer. If package.json changes, Docker reruns dependency installation.
Inefficient pattern
COPY . .
RUN npm ci
RUN npm run build
Because every source change invalidates the first copy, Docker might reinstall dependencies for every source edit.
Inspect and reduce size
docker build -t my-app .
docker images my-app
docker history my-app
Prefer alpine only when the extra work needed for native dependencies is understood. Smallness is not the only quality criterion: correctness and vulnerability surface also matter.
Docker stops cache reuse at the first changed input.
Common Interview Questions
Finished this lesson?
0 of 27 lessons done · 0% of the course

