Sub topic 1
How Images and Layers Work
Prerequisites
You should be able to run docker build, docker run, and read a simple Dockerfile. This chapter assumes you know that an image is a package used to create containers.
Images Are Built from Layers
A Docker image is made of read-only layers. Most Dockerfile instructions create a new layer. Each layer records the filesystem changes made by that instruction. Docker combines the layers into the filesystem that a container sees.
Layers are reusable. If two images share the same base image, Docker can store shared layers only once. A container adds a small writable layer above the image layers. Changes made inside that container do not change the original image.
Dockerfile Instructions and the Build Context
The build context is the set of files Docker can read during a build. The final argument to docker build usually selects it:
docker build -t example-app .Here, . sends the current directory as the context. COPY and ADD can use files from this context. They cannot read arbitrary files from the host.
A Dockerfile instruction such as RUN, COPY, or ENV can create a layer. RUN apt-get install ... may add downloaded packages, while a later deletion does not necessarily remove those bytes from earlier layers.
Ordering Instructions for the Build Cache
Docker caches completed steps. A change invalidates the changed step and later steps, so put stable instructions before frequently changing files.
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run buildChanging application source now reuses the dependency-install layer. Changing package.json invalidates that layer, which is necessary.
Trimming the Build Context with `.dockerignore`
A .dockerignore excludes files before Docker sends the context. Exclude dependencies, logs, environment files, and version-control data:
.git
node_modules
*.log
.env
Dockerfile
.dockerignoreThis reduces upload time and prevents accidental copying of local files. It does not replace secret management. Do not put secrets in the context at all.
Why Images Get Large
Image size commonly comes from large base images, build tools, dependency caches, copied source trees, and files created in earlier layers. Measure rather than guess:
docker image ls example-app
docker history example-appdocker image ls shows the total image size. docker history shows which instructions contributed layers, helping you find expensive steps.
Exercise
Why should dependency manifests be copied before the rest of the source code?
Show answer
Source changes can then reuse the cached dependency-install layer until the manifests change.