Images, layers and writing a Dockerfile
An image is a stack of tar layers plus a config. See which Dockerfile lines make layers, why order decides cache hits, and how multi-stage builds cut size.
What a container really isBuild artifacts and artifact repositories
Images, layers and writing a Dockerfile
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- An image is an ordered list of layers, each a tar archive of file changes, plus a JSON config saying what to run. At run time the layers are stacked into one filesystem.
- Instructions that change files, such as RUN, COPY and ADD, create layers. ENV, CMD, EXPOSE and similar only change the config.
- A file deleted in a later layer still exists in the earlier one, so the image does not shrink. Clean up in the same RUN that created the mess.
- The build cache reuses layers up to the first instruction whose inputs changed. Copy dependency manifests and install dependencies before copying source code.
- A multi-stage build compiles in one image and copies only the result into a small runtime image, leaving compilers and caches behind.
From “install these things” to a file you can ship
A container needs a root filesystem with your app and everything it depends on. You could build one by hand: start from a Debian directory, install Python, copy the code. Then do it again next week, exactly the same way, on a CI runner. Doing it by hand is how you get “works on my machine” back.
A Dockerfile is that recipe written down, and an image is what the recipe produces: a build artifact you build once and run anywhere with a Linux kernel. The interesting part is how the image is stored, because that decides how fast it builds and how big it is.
An image is layers plus a config
I fetched the official nginx image from Docker Hub’s registry API with curl, since there is no Docker on this Mac. Its manifest lists seven layers:
$ jq -c '.layers[] | {size, digest: .digest[0:19]}' manifest.json
{"size":29842182,"digest":"sha256:40748add9f4f"}
{"size":34053867,"digest":"sha256:7863f34d5b18"}
{"size":626,"digest":"sha256:9c2c223cd436"}
{"size":966,"digest":"sha256:0e963785aec6"}
{"size":404,"digest":"sha256:cf84a1d9ec18"}
{"size":1211,"digest":"sha256:2930fe57ac18"}
{"size":1398,"digest":"sha256:96b93a1524c5"}
Each layer is a gzipped tar of file changes, named by the SHA-256 of its bytes. I downloaded all seven and hashed them, and each hash matched its digest. The first is Debian 13, about 30 MB compressed. The second is nginx and its libraries, 34 MB. The last five are under 1.4 KB each. Listing the third:
$ tar -tzvf layer3.tgz
-rwxr-xr-x 0 0 0 1620 Nov 24 09:47 docker-entrypoint.sh
One file. The image config also keeps a history, one entry per Dockerfile instruction, and says which of them produced no layer:
$ jq -r '.history[] | [(.empty_layer//false|tostring), .created_by[0:60]] | @tsv' config.json
false # debian.sh --arch 'amd64' out/ 'trixie' '@1795392000'
true LABEL maintainer=NGINX Docker Maintainers <docker-maint@ngin
true ENV NGINX_VERSION=1.31.10
true ENV NJS_VERSION=1.0.2
true ENV NJS_RELEASE=1~trixie
true ENV ACME_VERSION=0.4.2
true ENV PKG_RELEASE=1~trixie
true ENV DYNPKG_RELEASE=1~trixie
false RUN /bin/sh -c set -x && groupadd --system --gid 101 ngi
false COPY docker-entrypoint.sh / # buildkit
false COPY 10-listen-on-ipv6-by-default.sh /docker-entrypoint.d #
false COPY 15-local-resolvers.envsh /docker-entrypoint.d # buildki
false COPY 20-envsubst-on-templates.sh /docker-entrypoint.d # buil
false COPY 30-tune-worker-processes.sh /docker-entrypoint.d # buil
true ENTRYPOINT ["/docker-entrypoint.sh"]
true EXPOSE map[80/tcp:{}]
true STOPSIGNAL SIGQUIT
true CMD ["nginx" "-g" "daemon off;"]
That maps straight onto a Dockerfile. RUN and COPY changed files, so they made layers. LABEL, ENV, ENTRYPOINT, EXPOSE, STOPSIGNAL and CMD only edited the config. Six COPY and RUN lines plus the Debian base make the seven layers. The 34 MB layer is one RUN that adds a user, installs nginx with apt-get and cleans up, all in a single instruction.
Why order and grouping matter
At run time the layers are stacked with a union filesystem such as overlayfs. A path in a higher layer hides the same path below. A deletion is recorded as a special whiteout file. So deleting a file in a later layer hides it but does not remove its bytes from the earlier layer. That is why the nginx image installs and cleans up in one RUN.
The build cache works layer by layer. For each instruction, the builder asks whether the inputs match last time: the previous layer, the command text, and for COPY the contents of the copied files. If they match, it reuses the layer. The first miss rebuilds that step and everything after it. Put what changes rarely first and what changes often last.
Think of a stack of transparent sheets on an overhead projector. You can add a sheet that covers a mark, but the mark is still on the sheet underneath, and if you change the third sheet you have to redraw every sheet above it.
Writing one
A Dockerfile for a Python notes API, written from Docker’s documentation on multi-stage builds and build best practices. I did not build it, because there is no Docker or BuildKit here. The python:3.14-slim tag exists on Docker Hub, which I checked with the registry API.
# syntax=docker/dockerfile:1
FROM python:3.14-slim AS build
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH=/opt/venv/bin:$PATH
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY src/ ./src/
FROM python:3.14-slim
RUN useradd --system --uid 10001 notes
COPY --from=build /opt/venv /opt/venv
COPY --from=build /app/src /app/src
ENV PATH=/opt/venv/bin:$PATH
WORKDIR /app
USER notes
EXPOSE 8080
CMD ["python", "-m", "src.server"]
What each choice buys:
requirements.txtbeforesrc/. A code change misses the cache only at the lastCOPY, so dependencies are not reinstalled on every commit.--no-cache-dir. pip’s download cache never lands in a layer.- Two stages. The
buildstage could hold compilers for packages with C extensions. Only the virtual environment and source are copied into the final stage. USER notes. The process does not run as root inside the container, which, as the last lesson showed, shares the host’s kernel.- Exec-form
CMD(a JSON array) runs Python directly as PID 1, so it receivesSIGTERMon shutdown instead of a shell swallowing it.
Add a .dockerignore listing .git, .venv and test data, so they are never sent to the builder. Build it with docker build -t notes-api:1.4.2 ..
About the video
“Docker Image BEST Practices - From 1.2GB to 10MB” is from Better Stack, published December 2024, 7 minutes 15 seconds. Its chapters cover choosing base images, layer caching, reducing the build context, layer squashing, multi-stage builds and tools such as Dive and Slim. It does not open an image’s layers the way this lesson does. Depot’s video in deeper does that, with docker inspect and Dive. English was judged from the title, description, channel and its English caption tracks.
Where this fits
You have an image on your laptop. Next, where it goes so servers can pull it, and how a server knows it got the image you built: registries, tags and image provenance.
Check yourself
Your Dockerfile does COPY . . then RUN pip install -r requirements.txt. Every code change reinstalls all dependencies. Why, and how do you fix it?
COPY . . changes whenever any file changes, which invalidates the cache for every later step. Copy requirements.txt alone, install, then copy the rest of the source.
You add RUN rm -rf /tmp/build-cache as a separate line and the image is the same size. Why?
The files still exist in the earlier layer that created them. The new layer only records a whiteout marking them deleted. Remove them in the same RUN that created them.
Why does setting ENV not add to the image's size?
ENV only changes the image config. No files change, so the history records it as an empty layer.
What does a multi-stage build leave out of the final image?
Everything from earlier stages that is not explicitly copied across, typically compilers, build tools, package caches and source files.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.