Skip to main content
CodeOath

Chapter 1 · About 12 minFree

Images, containers and the build cache

Learn how Docker images, layers and containers work, why the order of a Dockerfile decides build speed, and why a smaller base image helps.

Published by Hem Mankad, founder of CodeOath and a software engineer for more than eight years. Prepared with AI assistance.

The program that worked on one laptop

Paperlark's stock API is a small Node program. On Priya's laptop it runs. On the build server it fails because the server has an older Node. On the production machine it fails differently, because a system library the program quietly relied on is missing. None of the three machines is wrong; they simply differ, and "install the same things on all of them by hand" is a promise nobody keeps for long.

A container removes the differences by packaging the program together with everything it needs to run: the runtime, the libraries and the files, but not the operating system's kernel, which the container shares with its host. That package is an image. A running instance of an image is a container. The same image behaves the same way on a laptop, a build server and a production host, because they all unpack the same bytes.

This track covers the machinery around that idea: building images, running them, joining them to other services, keeping the code in Git, testing and shipping it through a pipeline, and watching it in production. Every Docker command and every number in this chapter comes from a real run with Docker 29.7 and the BuildKit builder, against a tiny Paperlark API: a server.js that answers JSON, one dependency (ms), and a package.json with its lock file. The base image was node:22-alpine, and the Node version inside it was v22.23.3 on the day of the run, which will have moved on by the time you read this. The commands run on any Docker installation, but the sizes and times will differ.

Image or container?

An image is a read-only template: a stack of file-system layers plus some settings such as the default command. A container is what you get when you start an image: a process, isolated from the host, with a thin writable layer on top of the image. It is the same relationship as a program on disk and a running process.

The writable layer is where the difference shows. A container was started from the image, a file was written inside it, and the container was removed. A new container from the same image had no such file:

$ docker run --name plab-c1 plab-good:2 sh -c 'echo hello > /tmp/note.txt; cat /tmp/note.txt'
hello
$ docker rm plab-c1
$ docker run --rm plab-good:2 sh -c 'ls /tmp/note.txt'
ls: /tmp/note.txt: No such file or directory

The file lived in the first container's writable layer and disappeared with the container. The image was untouched. This is why a container is described as disposable, and why anything that must survive, such as a database's files, has to live in a volume (a later chapter) and not in the container itself. The --rm flag removes a container when it exits, which is what you want for one-off commands.

Running an image

Starting a container needs the image name and, usually, a few flags. For the Paperlark API:

$ docker run -d --name plab-run2 -p 3000:3000 plab-good:2
$ curl http://127.0.0.1:3000/
{"shop":"paperlark","sessionMs":7200000,"node":"v22.23.3"}
$ docker logs plab-run2
listening on 3000

-d runs the container in the background, --name gives it a name you can use afterwards, and -p 3000:3000 publishes the container's port 3000 on the host's port 3000: host port first, container port second. Without -p the program inside is running and answering, but nothing on the host can reach it. The same image started without the flag made curl fail. This is also why EXPOSE 3000 in a Dockerfile is only documentation: it records the port, and does not open it.

Two commands answer most "what is it doing?" questions. docker logs <name> shows what the program wrote to standard output and standard error, so a containerised program should log there and not to a file. docker exec <name> <command> runs another command inside the running container. After docker exec plab-run2 sh -c 'echo x > /tmp/n.txt', the command docker diff plab-run2 listed C /tmp and A /tmp/n.txt: the container's writable layer had changed one directory and added one file, and nothing else. docker diff is a quick way to see what a container has been writing, and to find the paths that deserve a volume.

Tags, digests and layer sharing

An image name has a repository and a tag, such as node:22-alpine, and the tag is a movable label: the maintainers re-point it when they publish a fix. Every image also has a digest, a hash of its content, shown by docker image ls --digests; for node:22-alpine it began sha256:0a7108bf6c7b on the day of the run. A digest never moves. The build log printed the base image as node:22-alpine@sha256:0a7108bf..., which is how you tell that two builds really used the same base. A tag is good for readability, and a digest is good for reproducibility; teams that need identical rebuilds pin the digest and update it on purpose.

docker version showed a client and a server, both 29.7.2. The client is the docker command you type; the server is the daemon that builds and runs images. Images come from, and go to, a registry, such as Docker Hub or one run by your cloud provider: docker pull downloads an image and docker push uploads one. Because the daemon does the work, the same commands can drive a daemon on another machine.

For your own images, tag each build with something that identifies the code, such as the short Git commit (paperlark-api:3f2a91c), and also with a moving label like latest only if a deployment script depends on one. When something misbehaves in production, the tag tells you exactly which commit is running; a bare latest tells you nothing.

Layers are shared, which is why many images cost less than they look. The Paperlark image had 8 layers, and its first 4 were exactly the 4 layers of node:22-alpine; the two Dockerfiles shared their first 5 layers with each other. Docker stores each layer once, and a second image that starts from the same base adds only its own layers.

Layers and the build cache

An image is built from a Dockerfile, a list of instructions. Each instruction that changes the file system creates a layer, and Docker keeps the layers. When you build again, Docker reuses a layer from the last build if the instruction and everything above it are unchanged; as soon as one step has to run again, every step after it runs again too. So the order of instructions is a speed decision.

The obvious first Dockerfile for the Paperlark API looks like this:

FROM node:22-alpine
WORKDIR /app
COPY . .
RUN npm ci --omit=dev
CMD ["node", "server.js"]

It works, and it is slow in a way that grows with the project. COPY . . copies everything, so any edit to any file changes that layer, and then npm ci, which reinstalls the dependencies, runs again. After one line was added to server.js, the build output showed: WORKDIR /app CACHED, then COPY . . run, then RUN npm ci --omit=dev run again (2.3 seconds here, and minutes in a real project).

The fix is to copy in the order of how often things change. The dependency files change rarely, so copy them first and install; the source changes often, so copy it last:

FROM node:22-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY server.js ./
CMD ["node", "server.js"]

The first build ran every step. After the same edit to server.js, the second build reported COPY package.json package-lock.json ./ CACHED, WORKDIR /app CACHED and RUN npm ci --omit=dev CACHED, and only COPY server.js ./ ran, in 0.1 seconds. Installing dependencies is the expensive step, and it no longer depends on the source. The rule to remember: the least changing things go first.

docker history lists the layers and their sizes. For the finished image, the layer for npm ci was 2.78 MB, COPY server.js was 12.3 kB, and the base image underneath was far larger. A layer's size counts forever: deleting a file in a later RUN hides it but does not shrink the image, because the earlier layer still holds it. This was measured with an Alpine image whose Dockerfile wrote a 50 MB file in one RUN and removed it in the next: the image was 64.6 MB, against 12.1 MB when the same file was written and removed inside a single RUN. Clean up in the same instruction that creates the mess.

The instructions you use daily

A short list covers nearly every Dockerfile:

  • FROM names the base image and starts the build. Pin a tag (node:22-alpine), not latest.
  • WORKDIR sets the directory for the instructions that follow and for the running container, creating it if needed.
  • COPY brings files from the build context into the image. ADD also unpacks archives and fetches URLs, which is why COPY is the better default.
  • RUN executes a command at build time and keeps the result as a layer. Chain related commands with && so they share one layer.
  • ENV sets environment variables that persist in the image and the container. Use it for defaults, never for secrets: a value set this way was printed in full by docker history --no-trunc and by docker inspect on the image.
  • EXPOSE documents which port the program listens on; it does not publish the port.
  • USER makes the later instructions and the running process use a non-root account, which limits the damage if the program is compromised.
  • CMD and ENTRYPOINT define what runs when a container starts, covered in the next chapter.

Every instruction you do not need is a layer and a cache key you do not have to think about, so keep the file short.

One more line in that Dockerfile deserves a reason: npm ci rather than npm install. npm ci installs exactly what the lock file records and stops if the two files disagree. With ms changed to 2.1.2 in package.json and left at 2.1.3 in the lock file, it failed with npm ci can only install packages when your package.json and package-lock.json ... are in sync and the line Invalid: lock file's [email protected] does not satisfy [email protected]. In an image build that failure is the right outcome: a build that cannot reproduce yesterday's dependencies should not quietly produce a different image. Always copy the lock file along with package.json, since the layer cache also keys on it.

The build context and .dockerignore

When you run docker build ., the dot is the build context: the files the builder may send into the build. If the Dockerfile has COPY . ., everything in the folder goes into the image, including things that should never be there, such as node_modules from your laptop, .git, logs and local secrets files.

A 50 MB dummy file, big.bin, was added to the Paperlark folder to see the cost. Building the first Dockerfile (COPY . .) with no ignore file transferred a build context of 52.45 MB, which took 3.5 seconds, and produced an image of 293 MB. After adding a .dockerignore file with these lines, the context was 296 bytes and the image was 241 MB:

big.bin
node_modules
*.log
.git

The ignore file has two jobs: it keeps the context small and fast, and it keeps junk and secrets out of the image. It also keeps the cache stable, since an unrelated file that changes (a log, say) can no longer invalidate a COPY . . layer. Notice what the second Dockerfile did without any help: it copied only package.json, the lock file and server.js, so with BuildKit the 50 MB file was never transferred at all (only 100 bytes of context). Precise COPY lines and a .dockerignore file protect you twice over; use both.

Choosing a base image

The base image is most of your image. Three choices are common. A full image such as node:22 includes a general Linux system and many tools; on this machine it was 1.64 GB. A slim or Alpine variant leaves most of that out; node:22-alpine was 238 MB, about one-seventh. A distroless image has no shell or package manager at all, and is smaller still.

Smaller means faster to pull, less to patch and less for an attacker to use. The price is that Alpine uses a different C library (musl instead of glibc), and some compiled packages and debugging habits assume the larger system. The practical rule: start with the slim or Alpine variant of the language image, pin its major version, and switch to the full image only if something fails. Rebuild regularly, since a pinned tag still receives security fixes only when you rebuild on top of it.

Mistakes that recur

  • Copying everything first, then installing. Copy dependency files first.
  • No .dockerignore. The context is slow and the image carries junk.
  • latest as a tag. Two builds a week apart may differ; pin a version.
  • Secrets in ENV or COPY. They stay in the layers. Pass secrets at run time.
  • Deleting a big file in a later RUN. The earlier layer still holds it.
  • Running as root. Add a USER line.
  • Treating a container as a place to keep data. It is disposable.
  • Publishing nothing and wondering why it is unreachable. EXPOSE only documents the port; -p publishes it.
  • Putting a secret in the build. It is readable from the image's history and metadata, as the run showed.

Carry forward: an image is a template, a container a disposable running copy; layers are cached in order, so put the least changing instructions first; the build context is everything you send, so ignore the rest; and a smaller base image is faster and safer. The next chapter covers how a container starts, how images are made smaller with multi-stage builds, and how to run one safely.

Coming: the guide answers questions in a later release.