Images, layers and Dockerfiles
The union filesystem, layer caching, .dockerignore, and the Dockerfile order that makes rebuilds fast.
A container is a process with a restricted view of the machine: its own filesystem, its own network namespace, its own process table, and limits on memory and CPU that the kernel enforces. An image is the filesystem that process starts from, built once and shipped everywhere. Neither is a virtual machine — there is no guest kernel, which is why a container starts in milliseconds and why "it works in Docker" means "it works on this kernel with this filesystem", nothing more.
Images are layers
A Dockerfile is a list of steps, and every step that changes the filesystem produces a layer: a read-only diff over the one before it. The image is the stack; a container is the stack plus one writable layer on top that vanishes when the container is removed.
FROM eclipse-temurin:21-jre
COPY . /app # layer: the whole repository
RUN cd /app && ./mvnw package -DskipTests # layer: the build, and Maven's whole cache
CMD ["java", "-jar", "/app/target/app.jar"]Layers are content-addressed and shared: two images from the same FROM line share those layers on disk and over the network, and a pull fetches only what the host does not have. The consequence that shapes every Dockerfile is the build cache: a step is re-run only if its inputs changed — its command, and for COPY/ADD the files' contents — and once one step re-runs, every step after it re-runs too. The first attempt above copies the whole repository before building, so a one-line change to a lesson file invalidates the copy, which invalidates the build, which re-downloads every dependency.
Cache order: what changes least goes first
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw -B -q dependency:go-offline # cached until pom.xml changes
COPY src src
RUN ./mvnw -B -q package -DskipTests # re-runs on a source change; dependencies are already hereThe POM changes weekly, the sources change hourly, so the dependency download sits above the source copy and survives it. The same principle decides everything else in the file: base image, then OS packages, then dependencies, then code, then configuration. .dockerignore is the other half — target/, node_modules/, .git/, *.md — because a file that is not sent to the daemon cannot invalidate a COPY.
The base image
FROM is the decision with the longest consequences. Three questions:
- JDK or JRE? A build needs
javac; a running service needs only the runtime.eclipse-temurin:21-jreis roughly a third the size of the JDK image, and a smaller image is a smaller attack surface and a faster pull.jlinkcan go further — a runtime with only the modules the application uses. - Which OS?
-jammy/-noble(Ubuntu) and-alpineare the usual tags. Alpine is small and uses musl instead of glibc, which most Java code never notices and some native libraries do; Temurin's Alpine builds are fine for a Spring service, and Distroless (gcr.io/distroless/java21) has no shell at all, which is the most secure and the hardest to debug. - Which tag?
eclipse-temurin:21moves with every patch release;21.0.5_11-jre-jammydoes not. Pin, and let a bot (Dependabot handles Dockerfiles) open the upgrade — the same rule as the Testcontainers lesson'spostgres:16-alpine. This repository's runner image pins its base and every jar it bakes in, and says why in the file: a learner compiling against one Spring version while the harness has another is a failure that looks like the learner's mistake.
Multi-stage builds: build in one image, ship another
The JDK, Maven's cache and the sources are needed to build the jar and are dead weight around it. A multi-stage build uses one image to build and copies only the result into another:
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw -B -q dependency:go-offline
COPY src src
RUN ./mvnw -B -q package -DskipTests
FROM eclipse-temurin:21-jre-jammy
RUN useradd --system --uid 10001 app
WORKDIR /app
COPY --from=build --chown=app:app /src/target/app.jar app.jar
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]The final image has the JRE and one jar; the build stage is discarded. The Java-in-a-container lesson improves the last COPY with Spring Boot's layered jar, so that the dependencies and the application code are separate layers and a code change ships a few hundred kilobytes rather than the whole jar.
Not root
By default a container's process runs as root inside the container, which is root on the host's kernel with a narrower view. A vulnerability that lets an attacker run a command in the container then runs it as root, and container escapes are easier from there. USER app after a useradd is the fix, and it has consequences you meet immediately: the process cannot bind port 80 (use 8080 and let the load balancer map it), cannot write outside directories you chowned, and cannot install packages at run time, which it should not be doing anyway. This repository's runner goes one step further for the code it executes on behalf of learners — every submission container runs as 65534 (nobody) with --network=none, so the image bakes in every jar a problem could need, because at run time there is no way to fetch one.
Two more lines that belong in every service image: ENTRYPOINT in the exec form (["java", ...], a JSON array) so that Java is PID 1 and receives SIGTERM directly rather than through a shell that swallows it; and no credentials in any layer — a copied .env or a build argument holding a token is in the image's history forever, readable by anyone who can pull it.
Under the hood: how a union filesystem actually stacks layers
"A layer is a read-only diff" hides a real filesystem mechanism, and the mechanism is why the cache rule in this lesson works the way it does.
OverlayFS: one directory made of several
Docker's default storage driver on Linux is overlay2, built on the kernel's OverlayFS. OverlayFS takes several directories and presents them as one merged view without copying anything: a stack of lowerdirs (read-only — each image layer is one) and a single upperdir (read-write — the container's layer), combined into a merged mount that is what the process actually sees as its root filesystem. Reading a file walks the stack top-down and returns the first copy found, so a file untouched since the base image is read straight out of that base layer's directory on disk — it is never duplicated into the container's layer just because the container exists.
Writing is where "copy-on-write" earns its name. The upperdir starts empty. The first time a container modifies a file that lives in a lowerdir, OverlayFS copies that whole file up into the upperdir first (a "copy-up"), then applies the write there — the original in the read-only layer is never touched, which is exactly what lets many containers share the same image layers on disk simultaneously without stepping on each other. A brand-new file a container creates is written directly into the upperdir. A delete of a file that exists in a lowerdir cannot remove it from a read-only layer, so OverlayFS records the deletion as a small placeholder file (a "whiteout") in the upperdir that tells the merged view to hide that name — docker diff on a running container is reading exactly this: additions and modifications in the upperdir, and whiteouts standing in for deletions.
This is also why a large copy-up (a big file changed one byte at a time, or a directory rewritten by an in-place package manager) inside a container's writable layer can be surprisingly slow the first time: the cost is the whole-file copy, not the small edit.
Why COPY order is a cache-invalidation problem, not a style preference
Each Dockerfile instruction becomes exactly one layer with its own content hash. docker build walks the instructions in order and, for each one, checks whether a layer already exists in the cache for that exact instruction on top of the exact parent layer it would now run after — for RUN, the hash is the command string; for COPY/ADD, the hash is computed from the copied files' contents and metadata, not the instruction text (so editing a comment above a COPY never busts it, but touching one byte of a copied file does). The moment one instruction misses the cache, every instruction after it is rebuilt unconditionally — not because Docker re-checks them and finds they changed, but because their parent layer is now new content that was never hashed before, so there is nothing to look up a cache hit against.
That is the entire justification for "what changes least goes first" from earlier in this lesson: pom.xml changes on the order of weeks, src/ changes on the order of minutes, so the COPY pom.xml / dependency:go-offline pair sits above COPY src src — a source edit invalidates the COPY src layer and the package layer after it, but the dependency-download layer underneath is untouched and its (much larger, much slower) work is skipped. Reverse the order — copy src before pom.xml — and every source edit, which is nearly every build, reruns the dependency download too, because the layer holding the downloaded jars now sits after a layer that just changed.
Try it yourself
Reason through a cache invalidation
Given this Dockerfile:
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw -B -q dependency:go-offline
COPY src src
RUN ./mvnw -B -q package -DskipTestsA developer changes one line inside src/main/java/OrdersController.java and reruns docker build. Using the mechanism above — content-hashed layers, and what happens to every instruction after a cache miss — predict which instructions hit the cache and which rerun, and explain why the dependency:go-offline layer is unaffected even though it runs after the COPY mvnw pom.xml step that Docker re-evaluates.
Which layers rerun, and why the dependency layer survives
COPY mvnw pom.xml ./, COPY .mvn .mvn and RUN ./mvnw dependency:go-offline all hit the cache: none of mvnw, pom.xml or .mvn changed, so each instruction's content hash matches what is on disk from the last build, and its parent layer (the previous cached layer) is unchanged too, so the lookup succeeds. COPY src src misses, because the copied contents changed — that layer is rebuilt from the new file. RUN ./mvnw package -DskipTests then also reruns, not because Maven's command changed, but because its parent layer (the fresh COPY src src layer) is new content with no prior cache entry to match against; a cache lookup needs both the instruction and the exact parent layer to have been seen together before. The dependency layer is unaffected specifically because it sits before the source copy in the file — its inputs (pom.xml, .mvn) and its parent layer are both untouched by a source-only change, so the miss never reaches it.
Misconceptions
- "Deleting a file in a later
RUNshrinks the image back down." It does not. OverlayFS layers are immutable once written; a delete in a later layer is a whiteout marker that hides the file from the merged view, but the bytes stay in the earlier read-only layer and still ship with the image. The only way to actually drop them is to never write them into a layer that ends up in the final image — remove them in the same instruction that created them, or leave them behind in a discarded build stage. - "The build cache checks whether an instruction's text changed." For
COPY/ADDit checks the copied files' contents (and metadata like permissions), not the instruction line — a rewritten comment above aCOPYnever invalidates it, but a whitespace-only edit inside a copied file does, because the file's hash changed even though nothing meaningful did.
Sources
- Docker documentation, "About storage drivers" and "OverlayFS driver" — how
overlay2composes lowerdir/upperdir/merged and performs copy-up. - Docker documentation, "Build cache" (Dockerfile reference / build guide) — how instruction and layer hashes determine a cache hit, and why a miss cascades.
overlayfs(8)(Linux kernel documentation) — the copy-up and whiteout mechanics at the filesystem level.