Sub topic 1
What a Dockerfile does: images, containers, and layers
A Dockerfile is a text file of build instructions. Docker reads it and produces an image. Later, Docker starts a container from that image. People often blur these three things together, and the confusion causes real mistakes: secrets baked into images, images that stay large after a cleanup step, and data that disappears when a container is removed. This chapter builds the working model that the rest of the tutorial relies on.
Prerequisites
This chapter assumes you have:
- Basic command-line skills (running commands, reading output, editing a text file).
- Docker installed, with
docker versionworking for your user. - A rough idea of what a container is: an isolated process running on a shared host kernel.
- Some experience running an application, such as a Node.js or Go program, so that "install dependencies, then start the server" sounds familiar.
You do not need to have written a Dockerfile before.
Three objects, three lifetimes
| Object | What it is | Created by | Changes after creation? |
|---|---|---|---|
| Dockerfile | Text file with build instructions | You | Yes, you edit it |
| Image | Read-only filesystem snapshot plus metadata (default command, environment, user) | `docker build` | No, it is immutable |
| Container | A running (or stopped) instance of an image, with its own writable layer | `docker run` | Yes, while it exists |
The relationship is one-directional. A Dockerfile produces an image, and an image produces any number of containers. Editing the Dockerfile does not change existing images. Writing files inside a container does not change the image it came from.
Software engineers often compare this to a class and its instances. The image is the class definition, fixed once built. Each container is an instance with its own state.
What an image contains
An image holds two things:
- A filesystem: the files a process will see when it starts, such as
/bin,/usr/lib, your application code, and installed dependencies. - Metadata: the default command to run, environment variables, the working directory, the user, and exposed ports.
An image does not contain a kernel, and it does not contain a running process. A container shares the kernel of the host (or of the Linux VM that Docker Desktop runs). That is why containers start in milliseconds and why an image can be only a few megabytes.
Layers
An image's filesystem is not one blob. It is a stack of layers. Each layer stores the set of files that a build step added, changed, or deleted compared to the layer below it. Docker presents the stack as a single merged filesystem using a union filesystem (on most Linux installs the overlay2 driver).
Only some instructions add filesystem content. Others only change metadata.
| Instruction | Effect on the image |
|---|---|
| `FROM` | Starts from the layers of the base image |
| `RUN` | Runs a command at build time and stores the filesystem changes as a layer |
| `COPY`, `ADD` | Stores the copied files as a layer |
| `WORKDIR` | Sets the working directory (creates the directory if needed) |
| `ENV`, `EXPOSE`, `USER`, `CMD`, `ENTRYPOINT`, `LABEL` | Records metadata only, with no files of significance |
Layers are identified by a content hash, so Docker can share them. If ten images start from node:20-slim, the base layers are stored once on disk and downloaded once. Layers also drive the build cache, which a later chapter covers: if an instruction and its inputs have not changed, Docker reuses the stored layer instead of running it again.
A first worked example
Create an empty directory with a file named Dockerfile:
FROM alpine:3.20
RUN echo "hello" > /greeting.txt
RUN echo "from a second layer" >> /greeting.txt
CMD ["cat", "/greeting.txt"]Build it, inspect the layers, and run it:
docker build -t layers-demo .
docker history layers-demo
docker run --rm layers-demoThe docker history output lists the image's steps from newest to oldest. You will see the two RUN steps with small sizes (a few bytes each), the CMD step with size 0B, and below them the base image's own layers. The docker run command prints two lines: hello and from a second layer.
Here is what happened:
docker buildread the Dockerfile and started from thealpine:3.20layers.- It ran each
RUNcommand inside a temporary container and saved the filesystem difference as a new layer. - It recorded
CMDas metadata. - It tagged the result as
layers-demo. docker runcreated a container from that image, started theCMDprocess, and removed the container on exit because of--rm.
The container's writable layer
When you start a container, Docker adds one thin writable layer on top of the image's read-only layers. Every write the process makes goes there. This design is called copy-on-write: if a process modifies a file that lives in a lower layer, Docker copies the file up into the writable layer first and changes the copy.
You can see this directly:
docker run --name scratch alpine:3.20 sh -c "echo hi > /tmp/note.txt"
docker diff scratch
docker rm scratch
docker run --rm alpine:3.20 cat /tmp/note.txtdocker diff lists the added file /tmp/note.txt (marked with A). After docker rm, the writable layer is deleted. The last command fails with "No such file or directory", because a fresh container starts from the unchanged image.
The consequence is that anything a container needs to keep, such as database files or uploads, must be stored in a volume or bind mount, not in the container's own filesystem.
Build time and run time are separate
A frequent source of confusion is which things happen when.
- Build time:
FROM,RUN,COPY, and similar instructions execute duringdocker build. Their results are frozen into the image. - Run time:
CMDandENTRYPOINTdefine what starts duringdocker run. Nothing in them executes during the build.
So RUN npm install installs packages once, when you build. CMD ["node", "server.js"] starts the server every time you run a container. If you put the server start in a RUN instruction, the build will hang or finish with a server that is no longer running, because processes started during a build do not carry into containers.
Common errors and gotchas
Deleting a file in a later layer does not shrink the image
Layers only add. A rm in a later layer records a "whiteout" marker that hides the file, but the original bytes remain in the earlier layer. Try it:
FROM alpine:3.20
RUN dd if=/dev/zero of=/big.bin bs=1M count=50
RUN rm /big.binAfter building this, docker history shows a 50 MB layer, and the image is still about 50 MB larger than the base. The fix is to create and delete the file in the same instruction, so the layer never contains it:
FROM alpine:3.20
RUN dd if=/dev/zero of=/big.bin bs=1M count=50 && rm /big.binThis applies to package manager caches and to downloaded archives too. Clean up in the same RUN that created the mess, or use a multi-stage build (covered later).
Secrets in a layer stay in the image
Because deleted content remains in earlier layers, copying a credentials file or passing a token with RUN and removing it afterward does not make the image safe. Anyone who can pull the image can extract the layer. Keep secrets out of the build context and use the BuildKit secret mounts described in the last chapter.
`RUN cd` does not persist
Each RUN starts a new shell in the image's configured working directory. A cd in one RUN has no effect on the next. Use WORKDIR to set the directory for later instructions.
Changing a container does not change the image
If you install a tool inside a running container, the next container will not have it. Put the installation in the Dockerfile, rebuild, and run from the new image. Teams that skip this end up with environments nobody can reproduce.
Tags are mutable names
alpine:3.20 is a label that points at an image. The maintainers can move it to a newer build. For repeatable builds, pin a specific version tag, and for strict reproducibility, a digest such as alpine@sha256:.... Avoid latest, which tells you nothing about which version you got.
Where this chapter leads
The next chapter covers the structure of the file: instruction syntax, comments, and parsing rules. With the layer model in mind, each instruction in it has a visible cost and a visible effect on the image.
Exercise
You build an image whose Dockerfile has RUN curl -o /tmp/data.tar.gz https://example.com/data.tar.gz, then RUN tar -xzf /tmp/data.tar.gz -C /opt, then RUN rm /tmp/data.tar.gz. The image is still larger than the extracted data alone. Why, and how would you change the Dockerfile?
Show answer
The first RUN stores the downloaded archive in its own layer. The later rm only adds a whiteout marker in a new layer, so the archive's bytes remain in the image. Combine the steps into one instruction, for example RUN curl -o /tmp/data.tar.gz https://example.com/data.tar.gz && tar -xzf /tmp/data.tar.gz -C /opt && rm /tmp/data.tar.gz, so the archive never appears in a committed layer. Alternatively, stream it without saving a file, or fetch it in an earlier stage of a multi-stage build.
Exercise
You run a container, create /app/uploads/report.pdf inside it, then stop and remove the container with docker rm. You start a new container from the same image. Is the report there, and what should you use if it must survive?
Show answer
No. The file was written to the first container's writable layer, which is deleted with the container. The image is read-only and was never changed. Use a named volume or bind mount for /app/uploads so the data lives outside the container's layer.