Sub topic 1
What a Docker Image Is
Prerequisites
This chapter assumes you can use a terminal, have run a container with docker run, and have Docker Engine or Docker Desktop installed. You should also know that a container is an isolated process running on the host's kernel.
The working model
A Docker image is a read-only template that holds everything a container needs to start: a filesystem, plus metadata that says how to run it. When you run docker run, Docker creates a container from an image. One image can start many containers.
An image has three parts:
- Layers. Each layer is an archive of filesystem changes: files added, modified, or deleted. Stacked in order, the layers form the root filesystem the container sees.
- A config. This is a JSON document with the default command, entrypoint, environment variables, working directory, exposed ports, and the CPU architecture and operating system.
- A manifest. This is a JSON document that lists the config and each layer by its digest, a hash of its content.
The image does not include a kernel. The container uses the host's kernel, so an image only has to ship user-space files such as libraries, tools, and your application.
Seeing it in practice
Pull a small image and look at it:
docker pull alpine:3.20
docker image ls alpine
docker image inspect alpine:3.20 --format '{{.Config.Cmd}} {{.Os}}/{{.Architecture}}'
docker history alpine:3.20The inspect command prints the default command and the platform from the config. The history command lists the layers. Alpine is small, so you will see only one or two.
Images and containers are different things
An image never changes once built. When a container starts, Docker adds a thin writable layer on top of the image's read-only layers. Anything the container writes goes there. When you remove the container, that layer is deleted and the image is untouched.
You can check this:
docker run --name demo alpine:3.20 sh -c 'echo hello > /note.txt'
docker diff demo
docker rm demo
docker run --rm alpine:3.20 ls /note.txtdocker diff shows /note.txt as added. The final command fails with "No such file", because the new container starts from the unchanged image.
Common errors
- Treating a container as storage. Data written to the writable layer disappears with the container. Use a volume for data you must keep.
- Confusing the image ID with the name. A name like
alpine:3.20can be moved to a different image later. The ID, which comes from the image's content, cannot. - Expecting an image to run anywhere. The config records an OS and architecture. An
arm64image will not run natively on anamd64host.
Exercise
You run docker run ubuntu:22.04 touch /data.txt, then start a second container from the same image and look for /data.txt. Will the file exist, and why?
Show answer
No. The first container wrote the file to its own writable layer, which is deleted with the container. The image's read-only layers never changed, so the second container does not see the file.