Skip to content
Hands-on IT IT Drills

Day 2: Instructions in Detail

Goal: Extend the notes-api Dockerfile with ENTRYPOINT, ARG, LABEL, EXPOSE, USER, STOPSIGNAL and HEALTHCHECK, and understand why the container now stops cleanly in under a second. · Duration: approx. 75 min · Prerequisite: Day 1

Briefing

  • Shell form (CMD notes-api) starts /bin/sh -c …; the shell becomes PID 1 and doesn’t pass signals on. Exec form (CMD ["notes-api"]) starts the program directly as PID 1.
  • docker stop sends the stop signal (default SIGTERM) and after 10 seconds SIGKILL. If you wait 10 seconds, you have a signal problem.
  • ARG applies only at build time, ENV in the container as well. An ARG before FROM applies only to FROM.
  • HEALTHCHECK, USER, EXPOSE, LABEL and STOPSIGNAL write metadata into the image configuration, not files.
 docker stop ──SIGTERM──► PID 1 ──?──► notes-api
   Shell form:  PID 1 = /bin/sh -c …   signal fizzles ─► 10 s ─► SIGKILL
   Exec form:   PID 1 = notes-api      graceful shutdown in < 1 s

Drill 1: Shell form and the 10-second problem

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

The second copy lays the state from the end of Day 1 on top – even if you skipped it. First a counterexample from the companion code: the same image as on Day 1, but with a CMD in shell form that additionally writes the logs to a file.

cp "$LAB/code/tag02/Dockerfile.shell" notes-api/
tail -1 notes-api/Dockerfile.shell
docker build -f notes-api/Dockerfile.shell -t notes-api:shell notes-api 2>&1 | tail -3

Expected (abbreviated, may vary by version):

CMD notes-api 2>&1 | tee /tmp/notes-api.log
 1 warning found (use docker --debug to expand):
 - JSONArgsRecommended: JSON arguments recommended for CMD to prevent unintended
   behavior related to OS signals (line 7)

BuildKit warns. You start it anyway and look at who is PID 1:

docker run -d --name notes-api -e NOTES_API_KEY=lab-api-key-123 notes-api:shell
docker exec notes-api ps -o pid,args
/usr/bin/time -p docker stop notes-api
docker logs notes-api | tail -1
docker rm notes-api

Expected (abbreviated, may vary by version):

PID   COMMAND
    1 /bin/sh -c notes-api 2>&1 | tee /tmp/notes-api.log
    7 notes-api
    8 tee /tmp/notes-api.log
notes-api
real 10.21
user 0.02
sys 0.01
time=… level=INFO msg=listening addr=:8080 version=dev pid=7
notes-api

PID 1 is the shell. It receives SIGTERM, doesn’t pass it on to notes-api and doesn’t exit itself. After 10 seconds SIGKILL arrives, and shutdown complete is missing from the log: open requests would have been aborted.

Save your progress? Sign up for free

Drill 2: ENTRYPOINT and CMD

Now the exec form, and an ENTRYPOINT instead of CMD:

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 .
ENTRYPOINT ["notes-api"]
EOF
docker build -q -t notes-api:tag02 notes-api
docker run --rm notes-api:tag02 healthcheck; echo "Exit-Code: $?"
docker run --rm --entrypoint sh notes-api:tag02 -c 'echo "PID $$"; which notes-api'

Expected (abbreviated, may vary by version):

sha256:c41f…
Exit-Code: 1
PID 1
/usr/local/bin/notes-api

healthcheck after the image name is appended to the ENTRYPOINT: the container runs notes-api healthcheck. Exit 1, because no server is running. --entrypoint replaces the program itself.

Dockerfile docker run IMAGE docker run IMAGE healthcheck
CMD ["notes-api"] notes-api healthcheck (replaces CMD)
ENTRYPOINT ["notes-api"] notes-api notes-api healthcheck
ENTRYPOINT ["notes-api"] + CMD ["--help"] notes-api --help notes-api healthcheck
ENTRYPOINT notes-api (shell form) /bin/sh -c notes-api arguments ignored

And stopping?

docker run -d --name notes-api -e NOTES_API_KEY=lab-api-key-123 notes-api:tag02
docker exec notes-api ps -o pid,args
/usr/bin/time -p docker stop notes-api
docker logs notes-api | tail -2
docker rm notes-api

Expected (abbreviated, may vary by version):

PID   COMMAND
    1 notes-api
notes-api
real 0.31
user 0.02
sys 0.01
time=… level=INFO msg="signal received, shutting down"
time=… level=INFO msg="shutdown complete"
notes-api

notes-api is PID 1, receives SIGTERM directly and shuts down cleanly.

Save your progress? Sign up for free

Drill 3: PID 1 and --init

notes-api catches SIGTERM itself. Not every program does, and for PID 1 a special rule of the Linux kernel applies: signals without their own handler are ignored instead of terminating the process. sleep has no handler:

docker run -d --name notes-sleep golang:1.27-alpine sleep 300
/usr/bin/time -p docker stop notes-sleep 2>&1 | grep real
docker rm notes-sleep
docker run -d --init --name notes-sleep golang:1.27-alpine sleep 300
docker exec notes-sleep ps -o pid,args
/usr/bin/time -p docker stop notes-sleep 2>&1 | grep real
docker rm notes-sleep

Expected (abbreviated, may vary by version):

notes-sleep
real 10.18
notes-sleep
…
PID   COMMAND
    1 /sbin/docker-init -- sleep 300
    7 sleep 300
real 0.27
notes-sleep

--init puts docker-init in front as PID 1. It is based on tini, passes signals on to its child process and reaps zombie processes. You don’t need it for notes-api, but often for shell scripts and programs that start child processes.

Tip: The waiting time isn’t set in stone: docker stop -t 30 or docker run --stop-timeout 30 give a slow service more time. Fix signals first, then talk about timeouts.

Save your progress? Sign up for free

Drill 4: ARG, ENV and their scope

The demo Dockerfile in the companion code prints three variables, once before and once after a second ARG GO_VERSION:

grep -v '^#' "$LAB/code/tag02/scope/Dockerfile"
docker build --no-cache --progress=plain --build-arg BUILD_NOTE=hallo \
  -t notes-scope:tag02 "$LAB/code/tag02/scope" 2>&1 \
  | grep 'GO_VERSION=\[' | grep -v 'RUN echo'

Expected (build output abbreviated, may vary by version):

ARG GO_VERSION=1.27
FROM golang:${GO_VERSION}-alpine
ARG BUILD_NOTE=ohne-notiz
ENV APP_MODE=lab
RUN echo "GO_VERSION=[${GO_VERSION}] BUILD_NOTE=[${BUILD_NOTE}] APP_MODE=[${APP_MODE}]"
ARG GO_VERSION
RUN echo "nach erneutem ARG: GO_VERSION=[${GO_VERSION}]"
#6 0.142 GO_VERSION=[] BUILD_NOTE=[hallo] APP_MODE=[lab]
#7 0.118 nach erneutem ARG: GO_VERSION=[1.27]

The ARG before FROM applies only to FROM. Inside the stage it is empty until you declare it there again without a value; then it takes over the default value. --build-arg overrides the default value of BUILD_NOTE. Which of this ends up in the finished image?

docker image inspect --format '{{json .Config.Env}}' notes-scope:tag02 \
  | jq -r '.[]' | grep -E '^(APP_MODE|BUILD_NOTE|GO_VERSION)='
docker history --no-trunc --format '{{.CreatedBy}}' notes-scope:tag02 \
  | grep '^RUN' | cut -c1-60

Expected (abbreviated, may vary by version):

APP_MODE=lab
RUN |2 BUILD_NOTE=hallo GO_VERSION=1.27 /bin/sh -c echo "nach
RUN |1 BUILD_NOTE=hallo /bin/sh -c echo "GO_VERSION=[${GO_VERSION

ENV ends up in the configuration and applies in every container. ARG doesn’t, but its value is recorded in the history of every RUN that could see it.

Security: That’s why no secret belongs in an ARG, not even one “only needed at build time”. Day 11 pulls such a key out of the history, Day 13 shows the right way.

Save your progress? Sign up for free

Drill 5: The complete Dockerfile

cat > notes-api/Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
ARG GO_VERSION=1.27
FROM golang:${GO_VERSION}-alpine

LABEL org.opencontainers.image.title="notes-api" \
      org.opencontainers.image.description="Notiz-API aus dem Trainingslager" \
      org.opencontainers.image.source="https://example.com/docker-lab/notes"

WORKDIR /src
COPY . .
ARG VERSION=dev
RUN go build -ldflags "-X main.version=${VERSION}" -o /usr/local/bin/notes-api .

EXPOSE 8080
USER 65532:65532
STOPSIGNAL SIGTERM
HEALTHCHECK --interval=10s --timeout=2s --start-period=5s --start-interval=1s \
  CMD ["notes-api", "healthcheck"]
ENTRYPOINT ["notes-api"]
EOF
hadolint notes-api/Dockerfile && echo "hadolint: ok"

Expected:

hadolint: ok
Instruction Effect
ARG GO_VERSION before FROM Go version switchable in one place: --build-arg GO_VERSION=…
LABEL org.opencontainers.image.* OCI annotations: name, description, source
ARG VERSION + -ldflags "-X …" version baked into the binary at build time, visible at /version
EXPOSE 8080 documents the port; only -p publishes it
USER 65532:65532 process and healthcheck run without root (numeric, Day 9)
STOPSIGNAL SIGTERM signal for docker stop; the default anyway, explicit here
HEALTHCHECK … CMD [...] Docker checks regularly via exit code 0/1, without curl in the image

The companion code original is at ~/docker-lab/code/tag02/notes/notes-api/Dockerfile. Build with a version:

docker build -q --build-arg VERSION=0.2.0 -t notes-api:tag02 notes-api
docker image inspect notes-api:tag02 | jq '.[0].Config
  | {User, ExposedPorts, StopSignal, Entrypoint, Cmd, Healthcheck, Labels}'

Expected (abbreviated, may vary by version):

sha256:8d02…
{
  "User": "65532:65532",
  "ExposedPorts": { "8080/tcp": {} },
  "StopSignal": "SIGTERM",
  "Entrypoint": [ "notes-api" ],
  "Cmd": null,
  "Healthcheck": {
    "Test": [ "CMD", "notes-api", "healthcheck" ],
    "Interval": 10000000000,
    "Timeout": 2000000000,
    "StartPeriod": 5000000000,
    "StartInterval": 1000000000
  },
  "Labels": {
    "org.opencontainers.image.description": "Notiz-API aus dem Trainingslager",
    "org.opencontainers.image.source": "https://example.com/docker-lab/notes",
    "org.opencontainers.image.title": "notes-api"
  }
}

All durations are in nanoseconds. Image sizes, digests and times in this chapter will differ on your machine.

Save your progress? Sign up for free

Drill 6: Watch the healthcheck

docker run -d --name notes-api -p 127.0.0.1:8080:8080 \
  -e NOTES_API_KEY=lab-api-key-123 notes-api:tag02
docker ps --filter name=^notes-api$ --format '{{.Status}}'
sleep 3
docker ps --filter name=^notes-api$ --format '{{.Status}}'
docker inspect --format '{{json .State.Health}}' notes-api \
  | jq '{Status, FailingStreak, Last: .Log[-1].ExitCode}'
curl -s localhost:8080/version

Expected (abbreviated, may vary by version):

…
Up Less than a second (health: starting)
Up 3 seconds (healthy)
{
  "Status": "healthy",
  "FailingStreak": 0,
  "Last": 0
}
0.2.0

How the options work together:

  • --start-period=5s: failures in the first 5 s don’t count against --retries (default 3). A successful check during this time makes the container healthy.
  • --start-interval=1s: during the start phase, Docker checks every second instead of at the default interval of 5 s. The container becomes healthy quickly; during operation, --interval=10s applies afterwards.
  • --timeout=2s: a check that takes longer counts as failed.

Warning: --start-interval needs Docker Engine 25.0 or newer and a Dockerfile frontend 1.6.0 or later; with docker/dockerfile:1 and Docker 29 both are satisfied. Older engines don’t know the option.

Save your progress? Sign up for free

Drill 7: USER and STOPSIGNAL in operation

The container from Drill 6 is still running.

docker exec notes-api id
docker exec notes-api touch /src/spur; echo "Exit-Code: $?"
/usr/bin/time -p docker stop notes-api 2>&1 | grep real
docker logs notes-api | tail -2
docker rm notes-api

Expected (abbreviated, may vary by version):

uid=65532 gid=65532 groups=65532
touch: /src/spur: Permission denied
Exit-Code: 1
real 0.29
time=… level=INFO msg="signal received, shutting down"
time=… level=INFO msg="shutdown complete"
notes-api

UID 65532 has no entry in /etc/passwd, and that’s fine: the kernel only knows numbers. Because /src belongs to root, the process can’t write anything there. For the API that’s correct; it keeps everything in memory. More on permissions on Day 9.

Tip: docker exec -u 0 notes-api sh still opens a root shell for debugging. USER protects the service, not against someone who is allowed to operate the Docker daemon.

Save your progress? Sign up for free

Drill 8: Heredocs in RUN and COPY

Heredocs have been stable since Dockerfile frontend 1.4.0. RUN <<EOT passes several lines as a script to the shell, COPY <<EOT file writes the text as a file into the image.

grep -v '^#' "$LAB/code/tag02/heredoc/Dockerfile"

Expected:

FROM golang:1.27-alpine
ARG VERSION=dev

COPY <<EOT /etc/notes/banner.txt
notes-api ${VERSION} – gebaut im Trainingslager
EOT

COPY <<"EOT" /usr/local/bin/notes-info
echo "Banner: $(cat /etc/notes/banner.txt)"
echo "Laufzeit-User: $(id -u)"
EOT

RUN <<EOT
set -eu
chmod 0755 /usr/local/bin/notes-info
mkdir -p /var/lib/notes
date -u +%Y-%m-%d > /var/lib/notes/built
EOT

CMD ["notes-info"]

grep -v '^#' also filtered out the shebang line #!/bin/sh of notes-info; it is in the file. Build and run:

docker build -q --build-arg VERSION=0.2.0 -t notes-heredoc:tag02 \
  "$LAB/code/tag02/heredoc"
docker run --rm notes-heredoc:tag02
docker run --rm --user 65532 notes-heredoc:tag02

Expected (abbreviated, may vary by version):

sha256:1be7…
Banner: notes-api 0.2.0 – gebaut im Trainingslager
Laufzeit-User: 0
Banner: notes-api 0.2.0 – gebaut im Trainingslager
Laufzeit-User: 65532

Without quotes (<<EOT), BuildKit substitutes ${VERSION} at build time. With <<"EOT" the text stays literal, and $(cat …) is only evaluated at runtime. In the RUN heredoc, set -eu makes sure an error in the middle aborts the build; without it, as with any shell, only the exit code of the last line counts.

Tip: hadolint 2.14 trips over a heredoc whose end marker is directly followed by the next instruction (unexpected 'R' expecting a new line). A blank line after EOT fixes that and reads better anyway.

Save your progress? Sign up for free

Checkpoint

Today’s Dockerfile:

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

Expected:

# syntax=docker/dockerfile:1
ARG GO_VERSION=1.27
FROM golang:${GO_VERSION}-alpine

LABEL org.opencontainers.image.title="notes-api" \
      org.opencontainers.image.description="Notiz-API aus dem Trainingslager" \
      org.opencontainers.image.source="https://example.com/docker-lab/notes"

WORKDIR /src
COPY . .
ARG VERSION=dev
RUN go build -ldflags "-X main.version=${VERSION}" -o /usr/local/bin/notes-api .

EXPOSE 8080
USER 65532:65532
STOPSIGNAL SIGTERM
HEALTHCHECK --interval=10s --timeout=2s --start-period=5s --start-interval=1s \
  CMD ["notes-api", "healthcheck"]
ENTRYPOINT ["notes-api"]

hadolint has nothing to complain about:

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

Expected:

Exit: 0

The image runs as UID 65532:

docker image inspect --format '{{.Config.User}}' notes-api:tag02

Expected:

65532:65532

The healthcheck is in the image:

docker image inspect --format '{{json .Config.Healthcheck.Test}}' notes-api:tag02

Expected:

["CMD","notes-api","healthcheck"]

Challenge

Compare notes-api:shell with notes-api:tag02: How long does docker stop take, and does shutdown complete appear in the log?

Hint: time measures how long a command takes; docker logs can still read the logs of a stopped container.

Solution

First the shell form:

docker run -d --name notes-stop -e NOTES_API_KEY=lab-api-key-123 notes-api:shell
time docker stop notes-stop
docker logs notes-stop 2>&1 | tail -1
docker rm notes-stop

Expected (abbreviated, ID and times differ):

4ae1f1994964…
notes-stop

real    0m10.396s
…
time=… level=INFO msg=listening addr=:8080 version=dev pid=8
notes-stop

Then today’s exec form:

docker run -d --name notes-stop -e NOTES_API_KEY=lab-api-key-123 notes-api:tag02
time docker stop notes-stop
docker logs notes-stop 2>&1 | tail -1
docker rm notes-stop

Expected (abbreviated, ID and times differ):

c2fbaa868cd2…
notes-stop

real    0m0.379s
…
time=… level=INFO msg="shutdown complete"
notes-stop

One line of difference in the Dockerfile, ten seconds of difference on every deployment and every restart. 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:tag02
Deleted: sha256:…
…
Total:  …

Save your progress? Sign up for free

Enterprise Note

  • Kubernetes doesn’t evaluate the HEALTHCHECK from the image; liveness, readiness and startup probes take over there. The healthcheck stays useful for Docker and Compose, and the command notes-api healthcheck can be reused as an exec probe.
  • After SIGTERM, Kubernetes waits 30 s by default (terminationGracePeriodSeconds). A service that ignores signals delays every rollout by exactly this amount of time.
  • A numeric USER ID is a prerequisite for runAsNonRoot to be able to check it. OpenShift assigns a random UID with group 0 anyway; files the service must write then need group permissions.
  • Registries and scanners evaluate OCI labels such as org.opencontainers.image.source; many platform teams make them mandatory by policy (Day 10).
  • Build arguments are visible: in the history, in CI logs, in provenance attestations. For secrets there are build secrets (Day 13).