Sub topic 1
Images and Containers: What a Build Produces
Prerequisites
Assume you can run docker build, docker run, and read a basic Dockerfile. You should also know that an image is a packaged filesystem and configuration used to start containers.
Images and containers
A Docker build produces an image. An image contains application files, dependencies, and metadata such as the default command. Running an image creates a container. A container uses the image as its starting point and adds a writable layer for changes made while it runs.
The image layers are read-only and can be shared by multiple containers:
What an image layer is
A layer is a set of filesystem changes, such as adding a file or deleting a directory. Docker stacks layers in order. The final image view combines them into one filesystem.
When a container changes a file from a read-only layer, the storage driver usually copies that file into the writable layer first. This is called copy-on-write. Removing a file creates a deletion marker in the newer layer; it does not erase the older layer.
Which Dockerfile instructions create layers
RUN, COPY, and ADD normally create filesystem layers. ENV, LABEL, EXPOSE, USER, WORKDIR, and CMD mainly add image metadata. FROM selects the base image and starts the build from its existing layers.
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
CMD ["node", "server.js"]Here, the dependency manifest copy and npm ci produce filesystem changes. WORKDIR and CMD configure the image without adding application files.
> callout note > Combine related cleanup with the command that creates temporary files. Deleting a file in a later RUN step hides it from the final view but does not remove it from the earlier layer. >
How the build cache decides on a hit or miss
Docker checks whether an instruction and its relevant inputs match a previous build. For COPY, file contents in the build context matter. For RUN, the command and the filesystem state before it matter. A matching entry is a cache hit, so Docker reuses the previous result. Otherwise, it is a cache miss and Docker runs the instruction again.
After a miss, later instructions generally rebuild because their starting filesystem has changed.
Exercise
If only server.js changes in the example, which steps can remain cached?
Show answer
The base image, metadata, dependency-file copy, and npm ci can remain cached. The final COPY . . and later steps rebuild.