Platform Engineering · Lesson 141

Dockerfile Directives Part 1: Build the Image

Lesson 140 gave you five Dockerfile lines. This lesson is the other half of the build: nine directives, each with a working example and a rule for when to use it. FROM picks the base. RUN builds things. CMD and ENTRYPOINT start things. COPY and ADD bring files in. WORKDIR, ENV, and ARG set the stage. By the end you can read any Dockerfile line by line and say what each line does.

Difficulty: Intermediate · Know this first: Lesson 140 — Docker from Scratch: Your First Image, Built and Run

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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

The Dockerfile, mapped: base, copy, run, start

Start with a base image. Add one directive at a time until the app starts from a single command.

9 directives2 ways to copy1 value that vanishes
Base image
1 min
Workdir
1 min
Copy in
3 min
Run it
6 min
Env baked
1 min
Arg at build
1 min
Command runs
trip ends
Request / flowResponse · the way backFailure / dead end

Try it: change the inputs and watch the trip bend

The budget bar above shows three fixed stories. This simulator lets you write your own. Move a slider and watch the copy, the install, and the start 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: more code changes and a colder cache mean more rebuilds, and the install is the expensive one.

4

How many dependency layers the image has. Each one costs about 6 min to rebuild when the cache misses.

5

How many times a day the code changes. Every change rebuilds the code copy, and it rebuilds the install too when the code copy sits above it.

70

Share of layers the build reuses instead of rebuilding. A reused layer costs about 1 min in this model. A rebuilt layer costs about 6 min.

Try this: (1) Set deps to 10, code changes to 20, cache to 0. The copy is about 20 min, the run about 60 min, the command about 2 min, and the total is about 86 min. (2) Set deps to 1, code changes to 1, cache to 100. The copy is about 1 min, the run about 0 min, the command about 2 min, and the total is about 7 min. Same file. Only the inputs changed.

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Try it: edit the pipeline and check it

Here is the Dockerfile from this lesson, ready to edit. It uses all nine 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 ENTRYPOINT line, or change ARG to ENV and watch nothing fail, because both are real directives. The check only proves each line is present. The lesson text is what teaches when to use each one.

Press "Run the check" to see whether this pipeline does what the lesson asks.

Expected output when it passes: All nine directives are present: FROM, RUN, CMD, ENTRYPOINT, COPY, ADD, WORKDIR, ENV, and ARG. This file would build.

Basic to master

I take the same file four times here. First I learn the nine lines and what each one does. Then I learn the order that keeps the cache warm. Then I learn the traps: ARG that vanishes, shell form that eats signals. Last I read any Dockerfile like a checklist.

Basic — Nine lines, nine jobs

Definition: FROM names the base. WORKDIR names the folder. COPY brings files in from the build context. ADD brings files in too, and can also fetch a URL or unpack an archive. RUN executes a command at build time. ENV bakes a value into the image. ARG passes a value into the build. ENTRYPOINT is the command that always runs. CMD is the default argument to it.

Types:

  • FROM, which is always line one and names the base image.
  • COPY and ADD, which bring files into the image.
  • RUN, which executes a command at build time and makes a layer.
  • ENV and ARG, which set values, one for run time and one for build time.

Uses: I use this to read any Dockerfile line by line and say what each line does. 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 name: a directive spelled wrong, a file path that does not exist in the context, a CMD in shell form. It costs one careful read of the build error, which names the line it failed on.

Try it: Basic

I need a value at run time, not just at build time. Which directive holds it?

Now do it: Run the drill in the Try it box above: delete one line and run the check to see which directive the file lost.

Intermediate — Order is the cache

Definition: Docker reuses a layer when the instruction and its inputs have not changed. The first changed layer busts the cache for every layer below it. So the Dockerfile is ordered by how often things change: the base first, then the dependencies, then the code. A COPY of the code above the install means every code change rebuilds the install. The same COPY below the install means a code change costs one layer.

Types:

  • A stable layer, which changes rarely and sits at the top.
  • A changing layer, which changes daily and sits at the bottom.
  • A cache bust, which is one changed layer forcing every layer below it to rebuild.
  • A .dockerignore file, which keeps stray files out of the build context.

Uses: I use this when the build gets slow. I move the code copy below the install, and I keep stray files out of the context. Try it now: swap the two COPY lines in the Try it box and rebuild twice in your head, then fix the order and run the check. Then practice the ordering in the Docker labs.

Dimensions: As the app grows, the install grows, and the rebuild cost grows with it. What breaks is the order: one copy in the wrong place doubles the build time for the whole team. It costs a five minute review of the Dockerfile order, once a month.

Try it: Intermediate

Every code change rebuilds the install. What is in the wrong place?

Now do it: Run the drill in the Try it box above: swap the two COPY lines, rebuild twice in your head, then fix the order and run the check.

Advanced — ADD, ENTRYPOINT, and the traps

Definition: ADD does two things COPY does not: it fetches a file from a URL, and it unpacks a local archive into the image. Use ADD only when you need one of those two things. For plain files, COPY is the honest choice, because it does exactly what it says. ENTRYPOINT in exec form makes the app process 1, so signals reach it. In shell form, a shell becomes process 1, and docker stop waits the full timeout before it kills the container.

Types:

  • ADD for a URL, which fetches a file during the build.
  • ADD for an archive, which unpacks a tar file into the image.
  • ENTRYPOINT in exec form, the JSON list, which makes the app process 1.
  • ENTRYPOINT in shell form, the plain string, which wraps the command in a shell.

Uses: I use ADD only for a URL or an archive, and COPY for everything else. I use the exec form for ENTRYPOINT and CMD, and I test docker stop on every new image. Try it now: change the ENTRYPOINT line in the Try it box to shell form and notice the check still passes. The check proves the line is there. The lesson text is what tells you which form to use.

Dimensions: At ten times the images, the traps multiply. What breaks is the silent one: a shell-form ENTRYPOINT that eats SIGTERM, or an ADD that fetched a file nobody can see in the repo. It costs a review rule: COPY unless you can name the reason for ADD, exec form unless you can name the reason for shell form.

Find the line that busts the cache. A build that is slow every time is usually slow because of one line: a COPY that runs before the install, so every code change reinstalls every dependency. I find it by reading the Dockerfile from the top and asking, for each line, what changes when the code changes. The first line that changes on every code edit is the line that busts the cache. The fix is to move the install above it and the code copy below it.

  • Dependencies first, code last. That order is the whole cache strategy.
  • The first COPY that changes on every edit is the suspect.
  • Rebuild twice and compare the times. The second build should be fast.

Try it: run this check on a Dockerfile and find the cache-busting line.

# python3 cache-bust.py
lines = ["FROM node:20-slim", "WORKDIR /app", "COPY . .", "RUN npm ci", "COPY package.json ./"]
for i, line in enumerate(lines, 1):
    changes_on_code_edit = line.startswith("COPY .")
    print(i, line, "->", "BUSTS CACHE on every code edit" if changes_on_code_edit else "stable")

Expected: line 3, COPY . ., is flagged. The fix is to copy package.json first, run npm ci, and copy the code last. That is the order the lesson teaches, and this check proves why.

Try it: Advanced

I use ADD to copy a plain file from the repo. What should I use instead?

Now do it: Run the drill above: read the sample Dockerfile, find the cache busting line, and move the install above the code copy.

Master — Any Dockerfile, read like a checklist

Definition: At this level I read a Dockerfile I did not write and grade it in a minute: is the base pinned, are the copies ordered by change, is there one RUN per layer that needs one, does every value the app needs at run time come from ENV, is the start command in exec form. A Dockerfile that passes that check builds fast and runs clean. One that fails it is slow in exactly the places the checklist names.

Types:

  • A pinned base, which never moves under the build.
  • Ordered copies, which keep the cache warm across daily changes.
  • ENV for run time values, which survive the build.
  • Exec form start, which makes the app process 1.

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 order better than a page of rules. Try it now: open any Dockerfile you own and grade it. If the code copy sits above the install, that is the first gap to close.

Dimensions: At a hundred times the images, the Dockerfile is not the bottleneck, the drift is. What breaks is the base image nobody pinned, or the ten Dockerfiles that each order their copies differently. It costs a shared base image and a review checklist, not more rules.

ARG dies at the end of the build, and the leak is silent. An ARG that holds a secret is a secret that lives in the image history, because every build step is recorded. I check for it by scanning the Dockerfile for any ARG that is read after the build ends, or passed to a RUN that prints it. The fix is to never put a secret in an ARG at all. Secrets come in at run time, from a file or a secret store, never from the build.

  • Never put a secret in an ARG. The build history keeps it.
  • ARG is for versions and flags, not for passwords or tokens.
  • Scan the Dockerfile for ARG lines and ask what each one holds. A secret in the list is a leak.

Try it: scan a Dockerfile for ARG lines and flag the dangerous ones.

# python3 arg-scan.py
dockerfile = ["ARG APP_VERSION=1.0.0", "ARG API_TOKEN=secret123", "ARG NODE_ENV=production"]
for line in dockerfile:
    name = line.split()[1].split("=")[0]
    danger = any(word in name for word in ("TOKEN", "SECRET", "PASSWORD", "KEY"))
    print(line, "->", "SECRET IN BUILD, remove it" if danger else "safe")

Expected: APP_VERSION and NODE_ENV are safe, API_TOKEN is flagged. The token moves to run time, and the Dockerfile never sees it again.

Try it: Master

I scan a Dockerfile and find an ARG holding an API token. What is wrong?

Now do it: Open any Dockerfile you own and grade it against the four checks in the tier above. If the code copy sits above the install, that is the first gap to close.

Go deeper

Start with the full file below. It uses all nine 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
ARG APP_VERSION=1.0.0
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
ADD https://example.com/data.tar.gz /app/data/
COPY . .
ENTRYPOINT ["node"]
CMD ["dist/server.js"]

What the snippet means: the base is pinned, the build version arrives as an ARG, the work happens in /app, the run value is baked in with ENV, the dependency files are copied first, the install runs, a data archive arrives with ADD, the code is copied last, and the container starts with node and the server file as its default argument.

FROM is the only directive that must be first, and it can appear more than once in a multi-stage build, which is Lesson 145. Do this: run docker build --build-arg APP_VERSION=1.0.1 -t app:1.0.1 . and watch the build log. Expected output: the log shows the ARG value in use during the build. Then run docker run --rm app:1.0.1 printenv APP_VERSION. Expected output: nothing. The value is gone, and that proves the rule.

docker build --build-arg, flag by flag. A build arg is a value I pass into the build. It is not stored in the image, and it is not a secret.

  • --build-arg APP_VERSION=1.0.1 passes a value into an ARG in the Dockerfile for this build only. Without it the ARG keeps its default, or stays empty. The value does not get stored in the image. A build arg is not a secret.
  • -t names the image name:tag. Without it the image gets no name and no tag, and I cannot run it or push it by name.
  • . the build context: the folder Docker may copy files from. It is a path, not a flag, and it is required. A stray 2 GB file in that folder gets sent to the daemon on every build.

Flags you will meet next: --target builds only up to one stage, and --no-cache rebuilds every layer.

Try it: build once with --build-arg APP_VERSION=1.0.1 and once without it. Run each image with printenv APP_VERSION and read the value back. The two runs print different versions from the same Dockerfile.

To keep a build value at run time, copy it into ENV. Do this: add the line ENV APP_VERSION=$APP_VERSION right after the ARG line, rebuild, and run docker run --rm app:1.0.1 printenv APP_VERSION again. Expected output: the container prints 1.0.1. The ARG fed the ENV, and the ENV survived the build. That one line is the bridge between build time and run time.

ADD has two jobs and only two jobs: fetch a URL, and unpack a local archive. Do this: replace the ADD line with a COPY of a local data file and rebuild. Expected output: the build passes, and the file lands in the image without being unpacked. For plain files, COPY is the honest choice. Use ADD only when you need the fetch or the unpack, and say so in a comment. Practice all nine directives in the Docker labs.

At 10x the images, the shape holds and the numbers grow. At 100x, the design changes: the base image is shared, the Dockerfile order is reviewed, and the start command is always exec form. The nine directives never change. The discipline around them does. Lesson 142 covers the other eight directives, the ones that shape how the container runs.

ENTRYPOINT versus CMD, tested four ways

ENTRYPOINT and CMD look alike and behave differently, and the difference shows up when I pass an argument at run time. I test all four combinations: ENTRYPOINT alone, CMD alone, both together, and both with an argument on the command line. The argument replaces the CMD and is appended to the ENTRYPOINT. I run each combination and I write down what ran. That table is the one I check before I write either directive again.

# Four runs, one image. Run on a host with Docker.
# Dockerfile: FROM node:20-slim
#   ENTRYPOINT ["node"]
#   CMD ["server.js"]
docker build -t entry-test:1.0.0 .
docker run --rm entry-test:1.0.0
docker run --rm entry-test:1.0.0 worker.js
docker run --rm --entrypoint echo entry-test:1.0.0 hello

docker run --rm, flag by flag. A test container is a container I do not want to keep. --rm is the flag that makes it go away on its own.

  • --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.
  • --entrypoint echo replaces the image default entrypoint for this one run. The words after the image name become the arguments to the new entrypoint. Without it the image entrypoint runs, and the same words become its arguments instead. That is how one image answers two different questions.

Flags you will meet next: -it gives you a terminal inside the container, and -e sets an environment variable.

Try it: run the same image twice with --rm, once with an extra argument and once without. Both runs print and vanish. Then run it once without --rm and run docker ps -a. The stopped container is still there, holding its name.

Expected: the first run starts server.js, the second starts worker.js, the third prints hello and ignores both directives. If the second run still starts server.js, the CMD is in shell form and the argument never reached it.

Practice this in Lab 156 — Lesson 156 — Docker Lab: Build Your First Image and Run It: the Dockerfile in that lab uses the directives from this lesson, FROM through CMD, in one file you build yourself.

One time it broke

What broke

An app needed a version string at run time to print in its footer. The Dockerfile set it with ARG, because the value came from the build. The app printed nothing. The build log showed the value. The container did not have it. The ARG had done its job during the build and vanished, exactly as designed, and the app had no way to know.

Timeline

  • 10:02,I added ARG APP_VERSION=1.0.0 to the Dockerfile and used it in a RUN step to stamp the build.
  • 10:05,the build log showed the version, and I pushed the image.
  • 10:20,the app started, and the footer showed a blank where the version should be.
  • 10:30,I ran docker run --rm app:1.0.0 printenv APP_VERSION and got nothing back.
  • 10:35,I added ENV APP_VERSION=$APP_VERSION after the ARG line, rebuilt, and ran printenv again.
  • 10:40,the container printed 1.0.0, and the footer showed the version.

What changed after

Two things. First, every value the app needs at run time comes from ENV, and every ARG has a comment saying what it is for. Second, I test every new variable with printenv in a throwaway container before I trust it. Try it now: pick one variable in any Dockerfile you own, run printenv for it in a throwaway container, and see whether it survives the build.

If you remember nothing else

Build it yourself

Build a working image that uses all nine directives from this lesson, with the copies ordered so a code change does not rebuild the install. It passes when the image builds, the app prints its version at run time, and a one-line code change rebuilds only the last layer.

Build it, step by step

  • Write a Dockerfile with FROM, ARG, WORKDIR, ENV, COPY, RUN, ADD, ENTRYPOINT, and CMD, in that order, for the hello-docker app from Lesson 140.
  • Set the version as an ARG, copy it into ENV, and build with docker build --build-arg APP_VERSION=1.0.1 -t app:1.0.1 .
  • Run docker run --rm app:1.0.1 printenv APP_VERSION and confirm it prints 1.0.1, proving the value survived the build.
  • Change one line in server.js, rebuild, and read the log to confirm the install step says CACHED.
  • Run docker run --rm app:1.0.1 --version and confirm node prints its version, proving the run argument replaced CMD and kept ENTRYPOINT.

What success looks like

Success looks like this: the build log shows one step per directive. printenv prints 1.0.1. The second build shows CACHED on the install step. The --version run prints the node version instead of starting the server. If printenv prints nothing, the ENV line is missing or sits above the ARG line.

If it fails, check this

If the install rebuilds after a code change, the code copy sits above it. Move it below. If printenv prints nothing, the value was ARG only. Add the ENV line. If --version starts the server, ENTRYPOINT is missing and CMD is doing both jobs. Add the ENTRYPOINT line.

Next in this series
Lesson 142 — Dockerfile Directives Part 2: Run It Right