Lesson 141 built the image. This lesson shapes how the container runs: the port it declares, the data it keeps, the user it runs as, the label that names it, the check that asks if it is alive, the shell its commands use, the signal that stops it, and the trigger that fires in the next image down the line. Eight directives, each with a working example and a rule for when to use it.
Difficulty: Intermediate · Know this first: Lesson 141 — Dockerfile Directives Part 1: Build the Image
Every hop charges rent in milliseconds. The bar below is a worked example for this lesson's scenario — not a measurement from a live system — but the shape is honest: on a cache hit the trip is almost free, on a miss the kitchen eats the budget. Step through the lesson or switch the scenario and watch the bar change.
Extra diagram · from scratch to master
Start with a declared port. Add one directive at a time until the container runs as a non-root user, answers its healthcheck, and stops clean.
The budget bar above shows three fixed stories. This simulator lets you write your own. Move a slider and watch the volume work, the healthcheck, and the stop change in the budget bar, in the hop timings, and in the total. The numbers are a teaching example, not live measurements. The shape is the lesson: slow health answers and slow stops are what make a deploy drag.
How many volumes the container mounts. Each one costs about 1 min to check and mount in this model.
How often the healthcheck runs. A long interval means a stuck container is found late. A short interval finds it fast.
How long the runtime waits after SIGTERM before it kills the container. An app that ignores SIGTERM waits the whole timeout, every stop.
Try this: (1) Set volumes to 10, healthcheck interval to 5, stop timeout to 120. The volumes are about 10 min, the healthcheck about 13 min, the stop about 12 min, and the total is about 38 min. (2) Set volumes to 1, healthcheck interval to 60, stop timeout to 5. The volumes are about 1 min, the healthcheck about 2 min, the stop about 1 min, and the total is about 7 min. Same container. Only the inputs changed.
Three questions. No score is saved anywhere — this is just you against the material.
Here is the Dockerfile from this lesson, ready to edit. It uses all eight directives from this lesson. Change it, then run the check. The check looks for each directive by name.
Try breaking it on purpose: delete the HEALTHCHECK line, or change USER node to USER root. Run the check and watch it fail on the missing line. Then press Reset and try a change that keeps it passing, like changing the healthcheck interval to 15s.
Expected output when it passes: All eight directives are present: EXPOSE, VOLUME, USER, LABEL, HEALTHCHECK, SHELL, STOPSIGNAL, and ONBUILD. This file would build.
I take the same file four times here. First I learn the eight lines and what each one does. Then I learn the traps: a volume over the app files, a USER line in the wrong place. Then I learn the checks that keep a container honest. Last I read any Dockerfile like a checklist.
Definition: EXPOSE declares the port. VOLUME marks a folder whose data lives outside the container. USER sets the user the app runs as. LABEL sticks metadata on the image. HEALTHCHECK runs a command on a schedule to ask if the app is alive. SHELL picks the shell for RUN lines. STOPSIGNAL names the signal the runtime sends on stop. ONBUILD sets a trigger that fires when another image builds FROM this one.
Types:
Uses: I use this to read any Dockerfile and say what each line does at run time. Try it now: open the Try it box, delete one line, and run the check to see which directive the file lost. Then practice each directive in the Docker labs.
Dimensions: At low traffic everything is nearly free. What breaks first is the mix-up: EXPOSE mistaken for a published port, a volume mounted over the app folder, a USER line at the top that breaks the install. It costs one careful read of the error, which names the thing it could not do.
Definition: A volume mounted over the app folder hides the app files, because the mount covers what is underneath it. A USER line at the top breaks every RUN step that needs root. A shell-form ENTRYPOINT makes a shell process 1, so SIGTERM never reaches the app and docker stop waits the full timeout. Each trap has one fix: mount on an empty data folder, put USER after the install, and use the exec form.
Types:
Uses: I use this when a container misbehaves after a Dockerfile change. I check the mount path, the USER line position, and the start form, in that order. Try it now: move the USER line to the top of the Try it box and think through what breaks. Then put it back and run the check. Then practice the traps in the Docker labs.
Dimensions: As the team grows, the traps multiply. What breaks is the Dockerfile nobody reviewed: a volume over the code, a root user in prod, a stop that always waits. It costs a review checklist, not more rules.
Definition: A healthcheck proves the app can answer, not just that the process exists. The check runs inside the container, so it needs a tool in the image. The interval says how often it runs. The timeout says how long it may take. Three failed checks in a row mark the container unhealthy. An orchestrator removes an unhealthy container from traffic and starts a fresh one. Without the check, a stuck container keeps getting requests until a human notices.
Types:
Uses: I use this when a service goes quiet instead of failing loudly. I add a healthcheck that hits a real endpoint, and I test it by breaking the endpoint on purpose. Try it now: change the healthcheck interval in the Try it box to 15s and run the check. Then practice breaking and fixing health in the Docker labs.
Dimensions: At ten times the containers, the healthcheck is the difference between a bad deploy that fixes itself and one that pages a human at 2 AM. What breaks is the check that always passes: a check on the wrong port, or a check that tests the wrong thing. It costs one deliberate failure, to prove the check can go red.
Tune the health check from the detection time, not from a feeling. A health check with a 30 second interval and 3 retries takes 90 seconds to call a dead container unhealthy. That is 90 seconds of traffic going to a dead container. I work backwards from the time I can afford: if I need detection in 30 seconds, the interval times the retries must fit in 30. I set the start period long enough for a slow start, and the interval short enough to catch a real failure.
Try it: compute the detection time for three settings.
# python3 healthcheck-time.py
settings = [("slow", 30, 3), ("balanced", 10, 3), ("fast", 5, 2)]
for name, interval, retries in settings:
print(name, "- detection time (s):", interval * retries)
Expected: slow detects in 90 seconds, balanced in 30, fast in 10. If my budget is 30 seconds, only balanced and fast pass, and fast is the one I pick when the app starts quickly.
Definition: At this level I read a Dockerfile I did not write and grade it in a minute: is the port declared, is the data outside, does the app run as a non-root user, is there a healthcheck that can go red, is the start in exec form, does the stop finish fast. A Dockerfile that passes that check runs clean. One that fails it is slow or unsafe in exactly the places the checklist names.
Types:
Uses: I use this to review a setup I did not build: I open the Dockerfile and grade it against the four checks above. It is also how I teach the team: one bad Dockerfile, reviewed in public, teaches the traps better than a page of rules. Try it now: open any Dockerfile you own and grade it. If the app runs as root, that is the first gap to close.
Dimensions: At a hundred times the containers, the Dockerfile is not the bottleneck, the drift is. What breaks is the ten Dockerfiles that each handle users and health differently. It costs a shared base image and a review checklist, not more rules.
Signals decide how fast a container stops. A container that ignores SIGTERM waits 10 seconds and then gets killed. That is 10 seconds of deploy time on every rollout, and a shutdown that drops work in flight. I check that the app handles SIGTERM and that the STOPSIGNAL matches what the app listens for. Then I test it: stop the container and time it. A container that stops in 1 second is a container whose signal handling works. A container that always takes 10 seconds is a container that ignores the signal.
Try it: test signal handling with a tiny script, no Docker needed.
# A shell script that catches SIGTERM and exits cleanly. Run it, then stop it. cat > /tmp/graceful.sh <<'EOF' trap 'echo "got SIGTERM, shutting down cleanly"; exit 0' TERM echo "running, PID $$" while true; do sleep 1; done EOF bash /tmp/graceful.sh & sleep 1 kill -TERM %1 wait %1 echo "exit code: $?"
Shell redirects, piece by piece. The command is half the line. The redirects are the other half. They decide where the output goes and what happens when the command fails.
> file sends stdout to a file. Without it the output goes to the terminal and is gone when I scroll past it.2>/dev/null sends stderr to nowhere. Errors disappear. I use it only when I expect the error, like a cleanup command that may find nothing to clean. Hiding errors I do not expect is how a real failure goes unnoticed for a week.2>&1 sends stderr to the same place as stdout, so the log file holds both. Without it the log has the normal output and the errors are lost.& runs the command in the background and returns the prompt. The shell prints the job number and PID, and I save the PID when I need to stop it later.|| true turns a failing command into a success, so a script does not stop on it. I use it for cleanup steps that are allowed to find nothing.$? the exit code of the last command. 0 means it worked. Anything else means it failed, and the number sometimes says why.Flags you will meet next: >> appends instead of overwriting, and set -e stops a script on the first failure.
Try it: run a command that fails, once with 2>/dev/null and once without it. Without it the error prints. With it the error is gone, and only the exit code in $? says anything happened.
Expected: the script prints the shutdown line and exits with code 0. If it prints nothing and takes 10 seconds, the trap is missing and the app would be killed, not stopped.
Start with the full file below. It uses all eight directives from this lesson, and it is the file the Try it box checks. Do this: save it as Dockerfile, run docker build -t app:1.0.0 ., and watch each step. Expected output: the log shows one step per line, and the last line names the image app:1.0.0.
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
LABEL version="1.0.0" maintainer="platform-team"
EXPOSE 3000
VOLUME /data
USER node
HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:3000/health || exit 1
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
STOPSIGNAL SIGTERM
ONBUILD COPY package.json ./
CMD ["node", "dist/server.js"]
curl -f, flag by flag. This line lives inside a HEALTHCHECK. Its job is to fail loudly when the app is broken, so the runtime can see it.
-f fails the command on a 4xx or 5xx status and prints no body. Without it curl exits 0 even on a 404, and a healthcheck passes on an error page. That is the exact failure -f exists to catch.Flags you will meet next: --retry 3 retries a failed request, which is for a client, not a healthcheck.
Try it: run it against a healthy endpoint, then against a missing path. The healthy one exits 0. The missing one exits 22, and prints nothing. That exit code is what the healthcheck reads.
HEALTHCHECK, flag by flag. A container can be running and broken at the same time. The healthcheck is how the system tells the two apart.
--interval=30s how often the check runs. Without it the default is 30 seconds. A check that runs too often loads the app. One that runs too rarely finds a dead app late.--timeout=3s how long the check may take before it counts as failed. Without it the default is 30 seconds, and a hung app looks healthy for half a minute.CMD curl -f http://localhost:3000/health || exit 1 the check itself. curl -f fails on a 4xx or 5xx, so an error page counts as unhealthy. exit 1 is the failure the runtime reads. Without the || exit 1, a curl that fails for another reason could still exit 0, and the check would pass on a dead app.Flags you will meet next: --start-period=10s gives the app ten seconds to start before the checks count, and --retries=3 sets how many failures mark it unhealthy.
Try it: run the container, wait 30 seconds, and run docker ps. The status column should say healthy. Then break the health endpoint in a scratch copy, rebuild, and run it. The status flips to unhealthy after the failed checks.
What the snippet means: the base is pinned, the work happens in /app, the dependencies install before the code is copied, the image carries a version label, the port is declared, the data folder lives outside the container, the app runs as node, the healthcheck asks the app every 30 seconds, the shell fails a broken pipe, the stop signal is SIGTERM, the child build gets a trigger, and the container starts the server.
EXPOSE declares, -p publishes. Do this: run the image twice, once with docker run -d --name app1 app:1.0.0 and once with docker run -d -p 3000:3000 --name app2 app:1.0.0. Expected output: curl http://localhost:3000 fails for the first and answers hello for the second. The image is the same. The flag is the difference.
VOLUME keeps data, and the mount path decides what survives. Do this: run docker run --rm -v app-data:/data app:1.0.0 sh -c 'echo hello > /data/note.txt' and then docker run --rm -v app-data:/data app:1.0.0 cat /data/note.txt. Expected output: the second container prints hello. The data outlived the first container. Then run docker volume ls and find app-data in the list.
docker volume ls, flag by flag. A volume is invisible until it is listed. This is the command that proves the data survived.
docker volume ls lists the volumes on the host. Without it I cannot tell if the data survived, because the volume is invisible until it is listed.--filter name=app-data shows only volumes whose name matches. Without it I get every volume on the host, and the one I care about hides in the list.Flags you will meet next: docker volume create makes a volume by hand, docker volume inspect shows where it lives on disk, and docker volume prune deletes unused volumes, so I never run it blind.
Try it: run docker compose down, then docker volume ls --filter name=app-data. The volume is still listed. The data survived the down. Then run down -v and list again. It is gone.
docker run -v, flag by flag. A volume is where the data lives when the container does not. The -v flag is the mount point.
--rm removes the container when it stops. Without it the stopped container stays listed and keeps its name, so the next run with the same name fails with a name conflict.-v app-data:/data mounts a volume into the container at the given path. The part before the colon is the volume name. The part after is where it appears inside. Without it the data lives inside the container and dies with it.-d runs the container in the background and prints its ID, then returns the prompt. Without it the terminal stays attached to the app, and closing the terminal stops the container.-p 3000:3000 publishes a container port on the host. The order is host port first, container port second. Without it the port stays private inside the container network, and nothing on the host can reach it.--name hello names the container. Without it Docker picks a random name, and every later command has to use the ID or that random name.Flags you will meet next: --mount does the same job with named fields, and -v /host/path:/data mounts a host folder instead of a volume.
Try it: write a file into /data, remove the container, and run a new one with the same volume. Read the file back. It is still there. That is the proof the data lives in the volume, not the container.
HEALTHCHECK proves the app can answer. Do this: run the container, wait 30 seconds, and run docker ps. Expected output: the status column shows healthy. Then break the health endpoint in a scratch copy of the app, rebuild, and run it. Expected output: the status flips to unhealthy after three failed checks. A check you have never seen go red is a check you have not tested. Practice all eight directives in the Docker labs.
docker ps, flag by flag. ps shows what is running. The flags decide whether the stopped ones show up, and which columns I read.
--filter "status=exited" shows only containers that match. Without it ps shows every running container, and the stopped one I am looking for is not in the list at all.--format "{{.Names}} {{.Status}}" prints only the fields I name, using a Go template. Without it I get the full table.Flags you will meet next: -a shows stopped containers too, and --format '{{.Names}} {{.Ports}}' prints names and ports only.
Try it: stop a container, then run docker ps. It is gone from the list. Run docker ps --filter status=exited and it appears. The container did not vanish. The default view just hides stopped ones.
At 10x the containers, the shape holds and the numbers grow. At 100x, the design changes: the base image carries the USER and HEALTHCHECK lines, and the app Dockerfiles inherit them. The eight directives never change. The discipline around them does. Lesson 143 is where containers start talking to each other.
A USER directive that comes before the install means the install fails, because the user cannot write to the app folder. A VOLUME over the app folder means the app files vanish at run time, because the volume starts empty and hides what is underneath. I test both with a tiny image: build it, run whoami inside it, and list the app folder. The answers should be the non-root user and the app files present. If either is wrong, the directive is in the wrong place.
# Build a tiny image, then check who runs it and whether the files survived. # Dockerfile: # FROM node:20-slim # WORKDIR /app # COPY package.json ./ # RUN useradd -m appuser # USER appuser # CMD ["whoami"] docker build -t user-check:1.0.0 . docker run --rm user-check:1.0.0 docker run --rm user-check:1.0.0 sh -c "ls /app"
Expected: the first run prints appuser, the second lists package.json. If the first prints root, the USER line is missing or in the wrong place. If the second lists nothing, a volume is hiding the app folder.
A container kept serving errors for an hour, and nothing removed it. The process was running, so the runtime thought it was fine. The app had lost its database connection and answered every request with an error. There was no healthcheck, so nothing in the system knew the app was broken. The first human to notice was a user, not a monitor.
Two things. First, every image gets a healthcheck that hits a real endpoint, and the check is tested by breaking the endpoint on purpose. Second, I treat a container with no healthcheck as broken in review, the way I treat a deploy job with no rules. Try it now: open any Dockerfile you own and find its HEALTHCHECK line. If it has none, add one before the next deploy.
Build a working image that uses all eight directives from this lesson, runs as a non-root user, keeps its data outside the container, and proves its health on a schedule. It passes when the image builds, the container reports healthy, the data survives a restart, and the stop finishes fast.
Success looks like this: the build log shows one step per directive. whoami prints node. The file written by the first container is readable by the second. docker ps shows healthy. docker stop finishes in under 2 seconds. If the stop waits, the start form or the signal handling is the cause, not the image size.
If whoami prints root, the USER line is missing or sits above a later instruction that resets it. If the data is gone, the mount path is wrong or the volume name changed between runs. If the status never shows healthy, the healthcheck command is wrong or the endpoint does not exist. If the stop waits, check the ENTRYPOINT form first.