Skip to content
Hands-on IT IT Drills

Day 1: The First Dockerfile

Goal: Write your own Dockerfile for notes-api, tell images and containers apart, read layers and get the image into the local registry by tag and digest. · Duration: approx. 60 min · Prerequisite: Day 0

Briefing

  • A Dockerfile is a blueprint. Each instruction (FROM, WORKDIR, COPY, RUN, CMD) creates a step; the steps that change files become layers.
  • An image is the stack of layers plus configuration, immutable. A container is a running process on that image with its own writable layer on top.
  • A tag (notes-api:tag01) is a movable name, a digest (sha256:…) the fixed checksum of exactly one manifest.
 Dockerfile            Image notes-api:tag01           Container notes-api
 FROM golang:…  ──►   ┌─────────────────────────┐    ┌──────────────────────┐
 WORKDIR /src   ──►   │ RUN go build   (layer)  │    │ writable layer       │
 COPY . .       ──►   │ COPY . .       (layer)  │ ─► ├──────────────────────┤
 RUN go build   ──►   │ WORKDIR /src   (layer)  │    │ image (read-only)    │
 CMD [...]      ──►   │ golang:1.27-alpine …    │    └──────────────────────┘
                      │ Config: Cmd, Env, …     │
                      └─────────────────────────┘

Drill 1: Workspace for Day 1

source ~/docker-lab/setup/env.sh
mkdir -p ~/docker-lab/tag01 && cd ~/docker-lab/tag01
cp -R "$LAB/code/notes/." .
ls -A . notes-api

Expected:

.:
.env            .env.example    notes-api       notes-web       notes-worker
README.md

notes-api:
Dockerfile.naiv go.mod          go.sum          main.go

From today on, each day works in its own folder ~/docker-lab/tagNN. The original under ~/docker-lab/notes stays untouched.

Save your progress? Sign up for free

Drill 2: Five lines of Dockerfile

You write the Dockerfile from scratch, without the mistakes of the naive one: a smaller base image golang:1.27-alpine, no key in the image, CMD in exec form.

cat > notes-api/Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
FROM golang:1.27-alpine
WORKDIR /src
COPY . .
RUN go build -o /usr/local/bin/notes-api .
CMD ["notes-api"]
EOF
hadolint notes-api/Dockerfile && echo "hadolint: ok"

Expected:

hadolint: ok
Line Effect
# syntax=docker/dockerfile:1 BuildKit fetches the current Dockerfile frontend of version 1
FROM golang:1.27-alpine Base image: Go toolchain on Alpine Linux
WORKDIR /src creates /src and makes it the current directory
COPY . . copies the build context to /src
RUN go build … runs a command in the image; the result becomes a layer
CMD ["notes-api"] default command at startup, stores configuration only

The file is also available at ~/docker-lab/code/tag01/notes/notes-api/Dockerfile.

Save your progress? Sign up for free

Drill 3: Build

The last parameter is the build context: the folder that docker build sends to BuildKit. Only what lies inside it is visible to COPY.

docker build -t notes-api:tag01 notes-api

Expected (abbreviated, may vary by version):

[+] Building 21.4s (11/11) FINISHED                              docker:colima
 => [internal] load build definition from Dockerfile                      0.0s
 => resolve image config for docker-image://docker.io/docker/dockerfile:1  1.0s
 => [internal] load metadata for docker.io/library/golang:1.27-alpine     1.0s
 => [1/4] FROM docker.io/library/golang:1.27-alpine@sha256:…              9.8s
 => [internal] load build context                                         0.0s
 => [2/4] WORKDIR /src                                                    0.2s
 => [3/4] COPY . .                                                        0.0s
 => [4/4] RUN go build -o /usr/local/bin/notes-api .                      8.9s
 => exporting to image                                                    1.1s
 => => naming to docker.io/library/notes-api:tag01                        0.0s

No more warnings: exec form for CMD and no ENV with a key. If you build again right away, every step shows CACHED and the build takes one second (Day 4).

docker image ls --format '{{.Repository}}:{{.Tag}}  {{.Size}}' \
  | grep -E '^(notes-api|golang):'

Expected (may vary by version):

notes-api:tag01  340MB
golang:1.27-alpine  263MB

Image sizes, digests and build times in this book will differ on your machine. Compare the ratio: a third of the naive image, but still far more than the binary.

Save your progress? Sign up for free

Drill 4: Image versus container

First start without a key:

docker run --rm notes-api:tag01; echo "Exit-Code: $?"

Expected (abbreviated, may vary by version):

time=… level=ERROR msg="start abgebrochen" err="NOTES_API_KEY oder …"
Exit-Code: 1

Good: the key doesn’t belong in the image, it is added at startup. Now two containers from the same image:

docker run -d --name notes-api -p 127.0.0.1:8080:8080 \
  -e NOTES_API_KEY=lab-api-key-123 notes-api:tag01
docker run -d --name notes-api-2 -p 127.0.0.1:8081:8080 \
  -e NOTES_API_KEY=lab-api-key-123 notes-api:tag01
curl -s -X POST localhost:8080/notes -H 'X-API-Key: lab-api-key-123' \
  -d '{"text":"nur in Container 1"}'
curl -s localhost:8080/notes; curl -s localhost:8081/notes
docker ps --filter name=^notes-api --format '{{.Names}}\t{{.Image}}\t{{.Ports}}'

Expected (abbreviated, IDs differ):

{"id":"3a7e…","text":"nur in Container 1"}
[{"id":"3a7e…","text":"nur in Container 1"}]
[]
notes-api-2   notes-api:tag01   127.0.0.1:8081->8080/tcp
notes-api     notes-api:tag01   127.0.0.1:8080->8080/tcp

One image, two independent processes. Each container also has its own writable layer:

docker exec notes-api sh -c 'echo spur > /tmp/spur.txt'
docker diff notes-api
docker exec notes-api-2 ls /tmp

Expected (may vary by version):

C /tmp
A /tmp/spur.txt

A means added, C changed. notes-api-2 doesn’t see the file; the image stays unchanged. With docker rm -f the trace is gone:

docker rm -f notes-api notes-api-2

Warning: What a container writes at runtime disappears with it. Data that should persist belongs in a volume, not in the container layer.

Save your progress? Sign up for free

Drill 5: Read layers

docker history --format 'table {{.CreatedBy}}\t{{.Size}}' notes-api:tag01 | head -7

Expected (abbreviated, may vary by version):

CREATED BY                                      SIZE
CMD ["notes-api"]                               0B
RUN /bin/sh -c go build -o /usr/local/bin/no…   77.1MB
COPY . . # buildkit                             9.63kB
WORKDIR /src                                    0B
WORKDIR /go                                     0B
RUN /bin/sh -c mkdir -p "$GOPATH/src" "$GOPA…   0B

At the top are your four instructions, below them those of the base image. CMD has 0 bytes: it is only configuration. That is shown by docker image inspect:

docker image inspect notes-api:tag01 \
  | jq '.[0] | {Arch: .Architecture, Cmd: .Config.Cmd,
                Workdir: .Config.WorkingDir, Layers: (.RootFS.Layers | length)}'

Expected (abbreviated, may vary by version):

{
  "Arch": "arm64",
  "Cmd": [
    "notes-api"
  ],
  "Workdir": "/src",
  "Layers": 8
}

Why is the RUN layer 77 MB when the program is small? Take a look:

docker run --rm notes-api:tag01 \
  du -sh /usr/local/bin/notes-api /root/.cache/go-build /go/pkg/mod

Expected (may vary by version):

8.9M    /usr/local/bin/notes-api
67.0M   /root/.cache/go-build
1.4M    /go/pkg/mod

The Go build cache and the modules sit in the layer too. Whatever a RUN writes stays in the image, even if nobody needs it anymore. Day 4 moves the cache into a cache mount, Day 5 throws away the whole toolchain with multi-stage.

Tip: Whatever comes after the image name (du -sh …) replaces CMD. That’s why du ran above instead of notes-api. Day 2 shows how to control this deliberately.

Save your progress? Sign up for free

Drill 6: Tag and digest

A tag is just a name. For the registry, the image gets a second one:

docker tag notes-api:tag01 localhost:5001/notes-api:tag01
docker push localhost:5001/notes-api:tag01
OLD=$(docker image inspect --format '{{index .RepoDigests 0}}' \
  localhost:5001/notes-api:tag01)
echo "$OLD"

Expected (abbreviated, digests differ):

The push refers to repository [localhost:5001/notes-api]
…: Pushed
tag01: digest: sha256:4e0c… size: 1609
localhost:5001/notes-api@sha256:4e0c…

RepoDigests only exists after a push or pull: the digest is the checksum of the manifest stored in the registry. Now you change the code and push the same tag again:

echo '// Tag 1: Tag verschoben' >> notes-api/main.go
docker build -q -t localhost:5001/notes-api:tag01 notes-api
docker push -q localhost:5001/notes-api:tag01
curl -sI localhost:5001/v2/notes-api/manifests/tag01 | grep Digest
echo "alt: ${OLD#*@}"

Expected (abbreviated, digests differ):

sha256:b71d…
localhost:5001/notes-api:tag01
Docker-Content-Digest: sha256:2f6537a9d0c7…
alt: sha256:4e0c…

The tag tag01 now points to a different digest. Anyone pulling notes-api:tag01 gets the new state from now on without noticing. But the old state isn’t lost; it can still be fetched by its digest:

curl -sI "localhost:5001/v2/notes-api/manifests/${OLD#*@}" | head -1

Expected:

HTTP/1.1 200 OK

localhost:5001/notes-api@sha256:… always returns exactly the same image. That’s why Day 8 and Day 10 pin by digest. Undo the code change:

cp "$LAB/code/notes/notes-api/main.go" notes-api/main.go

Save your progress? Sign up for free

Drill 7: What’s still missing

Compared with the naive image from Day 0 (1.07GB), notes-api:tag01 has shrunk to a third, and the key is no longer in the configuration:

docker image inspect --format '{{json .Config.Env}}' notes-api:tag01 \
  | grep -c NOTES_API_KEY
docker image inspect --format 'User: "{{.Config.User}}"' notes-api:tag01
docker run --rm notes-api:tag01 id

Expected (may vary by version):

0
User: ""
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),…

No USER set, so the process runs as root. A healthcheck, a version string and clean signal handling are also missing; and the Go toolchain is still in the image. Day 2 takes care of the first points, the toolchain disappears on Day 5. The key is passed at runtime; that’s enough for today. Day 14 explains why -e isn’t the end of the story.

Save your progress? Sign up for free

Checkpoint

Today’s Dockerfile:

cd ~/docker-lab/tag01
cat notes-api/Dockerfile

Expected:

# syntax=docker/dockerfile:1
FROM golang:1.27-alpine
WORKDIR /src
COPY . .
RUN go build -o /usr/local/bin/notes-api .
CMD ["notes-api"]

hadolint has nothing to complain about:

hadolint notes-api/Dockerfile; echo "Exit: $?"

Expected:

Exit: 0

tag01 is in the registry:

curl -s localhost:5001/v2/notes-api/tags/list | jq -c

Expected:

{"name":"notes-api","tags":["naiv","tag01"]}

main.go is back in its original state (Drill 6):

diff notes-api/main.go "$LAB/code/notes/notes-api/main.go" && echo gleich

Expected:

gleich

Challenge

How much of the image notes-api:tag01 actually belongs to you, and how much to the base image? Find your own layers with size and command, and compare the size of both images.

Hint: The history of the base image is the bottom part of your image’s history; the difference in line counts is your layers.

Solution

BuildKit only loaded the base image internally; docker pull adds it as an image with a tag. How many layers do both images have?

docker pull -q golang:1.27-alpine
docker history -q notes-api:tag01 | wc -l
docker history -q golang:1.27-alpine | wc -l

Expected:

docker.io/library/golang:1.27-alpine
14
10

The difference is your layers; they are at the top of the history:

docker history notes-api:tag01 | head -5

Expected (abbreviated, may vary by version):

IMAGE          CREATED         CREATED BY                                      SIZE
b865b4fa6492   3 minutes ago   CMD ["notes-api"]                               0B
<missing>      3 minutes ago   RUN /bin/sh -c go build -o /usr/local/bin/no…   112MB
<missing>      4 minutes ago   COPY . . # buildkit                             32.8kB
<missing>      27 hours ago    WORKDIR /src                                    8.19kB

And the size of both images:

docker image ls golang:1.27-alpine
docker image ls notes-api:tag01

Expected (abbreviated, may vary by version):

IMAGE                ID             DISK USAGE   CONTENT SIZE   EXTRA
golang:1.27-alpine   d200d2dd76b0        382MB         75.5MB
IMAGE             ID             DISK USAGE   CONTENT SIZE   EXTRA
notes-api:tag01   b865b4fa6492        524MB          106MB

14 minus 10: four layers are yours, about 140 MB of 524 MB. About three quarters of the image are the Go toolchain and Alpine, which nobody needs at runtime. And of your quarter, the largest part is build cache. Finally, clean up:

docker ps -a --filter name=^notes- --format '{{.Names}}' | xargs -r docker rm -f
docker image ls --format '{{.Repository}}:{{.Tag}}' \
  | grep -E '^(notes-|localhost:5001/)' | xargs -r docker rmi
docker buildx prune --builder docker-lab --all --force

Expected (abbreviated, names, IDs and sizes differ):

Untagged: notes-api:tag01
Deleted: sha256:…
…
Total:  …

Save your progress? Sign up for free

Enterprise Note

  • Image tags like latest or tag01 are only a hint in production. Deployments reference the digest; most registries additionally allow “immutable tags”.
  • The build context is a security boundary: anything in it can get into the image via COPY. That’s why CI builds from a clean checkout, never from a working folder (Day 3).
  • In companies, base images like golang:1.27-alpine come from a vetted mirror and are updated centrally (Day 8).
  • Runtime configuration and secrets come from the platform (Kubernetes Secret, Vault/OpenBao, CI variables), never from the image (Day 14).
  • In production, docker push is done by the pipeline with a robot account, not by the developer laptop.