Practice: Dockerfiles
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
A teammate sends you a ShopLite Dockerfile that works, but the image is 874 MB, runs as root and takes a minute to rebuild. Find each mistake and fix it with what you learned in this module.
Mistake 1: latest tag and a JDK at run time
An unpinned base image is a FROM line with no tag or with latest. It changes whenever the publisher pushes a new version, so the same Dockerfile can build a different image next week.
Example 1 is the Dockerfile under review, with the size and the user it produces. The first mistake is on its first line.
Example 1 · The Dockerfile under review
Runs in: a terminal with Docker installed
FROM eclipse-temurin:latestWORKDIR /appCOPY . .RUN ./mvnw -B dependency:go-offlineRUN ./mvnw -B package -DskipTestsEXPOSE 8080CMD java -jar target/shoplite-api-1.2.0.jar# after: docker build -t shoplite-api:bad . && docker run -d --name shop-bad -p 8080:8080 shoplite-api:bad# docker images shoplite-api:bad# docker exec shop-bad whoamiREPOSITORY TAG IMAGE ID CREATED SIZE shoplite-api bad e7b90d4c1f56 2 minutes ago 874MB root
What this code does
- It builds and runs, which is why these mistakes survive in real projects: nothing fails until a slow build, a large pull or a security scan.
- 874 MB comes from the JDK base,
COPY . .(withtarget/and.git) and Maven's~/.m2downloads, all in the final image. Your size will differ.
A new Java version can break your app without any change on your side. The latest Temurin image is also a full JDK: a running Spring Boot app needs only a JRE, so the compiler, jshell and other tools are dead weight and more code that can have security holes.
Fix both: build on eclipse-temurin:25-jdk, run on eclipse-temurin:25-jre.
Fix the error
Fix the lines a linter flags
Read the linter message, then pick the line that fixes it.
Round 1 of 2
A linter checks the Dockerfile before the build.
Error
Dockerfile:1 DL3007 warning: Using latest is prone to errors if the image will ever update. Pin the version explicitly to a release tag
Mistake 2: COPY . . before pom.xml
Cache order is the rule that Docker reuses each step until the first step whose instruction or input files changed; that step and every step below it run again.
Example 2 predicts which steps rebuild when you change a controller, and when you change pom.xml.
Example 2 · Predicting rebuilds with the good order
import java.util.List;
record Step(String instruction, List<String> inputs) { boolean uses(String changedFile) { for (String input : inputs) { if (changedFile.equals(input) || changedFile.startsWith(input + "/")) { return true; } } return false; }}
public class RebuildPredictor { // Docker reuses each step until the first one whose instruction or input files changed. // From that step on, every step runs again. static void predict(List<Step> steps, String changedFile) { System.out.println("Changed: " + changedFile); boolean rebuilding = false; for (Step step : steps) { if (!rebuilding && step.uses(changedFile)) { rebuilding = true; } System.out.println(" " + (rebuilding ? "RUN " : "CACHED ") + step.instruction()); } }
public static void main(String[] args) { List<Step> good = List.of( new Step("FROM eclipse-temurin:25-jdk AS build", List.of()), new Step("COPY mvnw pom.xml ./", List.of("mvnw", "pom.xml")), new Step("COPY .mvn .mvn", List.of(".mvn")), new Step("RUN ./mvnw -B dependency:go-offline", List.of()), new Step("COPY src src", List.of("src")), new Step("RUN ./mvnw -B package -DskipTests", List.of()));
predict(good, "src/main/java/com/shoplite/product/ProductController.java"); predict(good, "pom.xml"); }}Changed: src/main/java/com/shoplite/product/ProductController.java CACHED FROM eclipse-temurin:25-jdk AS build CACHED COPY mvnw pom.xml ./ CACHED COPY .mvn .mvn CACHED RUN ./mvnw -B dependency:go-offline RUN COPY src src RUN RUN ./mvnw -B package -DskipTests Changed: pom.xml CACHED FROM eclipse-temurin:25-jdk AS build RUN COPY mvnw pom.xml ./ RUN COPY .mvn .mvn RUN RUN ./mvnw -B dependency:go-offline RUN COPY src src RUN RUN ./mvnw -B package -DskipTests
What this code does
- A simplified model of the cache: a step reruns when it copies a changed file, and everything after it reruns too. (Docker also reruns a step whose instruction text changed.)
- A controller change reuses the dependency download; only a
pom.xmlchange downloads again. That is the whole point of copyingpom.xmlfirst.
COPY . . makes every file an input of the first copy. Change one controller and the copy changes, so dependency:go-offline downloads every library again. Copy mvnw, .mvn and pom.xml first, download dependencies, and copy src last.
Predict the output
Which step downloads again?
Pick the first step that runs after the edit.
Round 1 of 2
You edit ProductController.java in this bad order.
Mistake 3: running as root
A non-root user is an account with limited rights, created in the final stage with groupadd and useradd and switched on with USER. With no USER line the app runs as root (uid 0).
Two lines in the final stage fix the root problem: create a system user, then switch to it.
RUN groupadd --system spring && useradd --system --gid spring --no-create-home springUSER spring:spring# check after a build:docker inspect --format '{{.Config.User}}' shoplite-api:1.2.0 # spring:springA bug that lets an attacker run code gives them root inside the container, write access to the jar and more power if they escape. Put USER just before ENTRYPOINT. Leave the jar owned by root so the app can read it but not change it.
Mistake 4: shell-form CMD
Shell form is a command written as plain text, like CMD java -jar app.jar. Docker runs it as /bin/sh -c "...", so the shell is PID 1 instead of java.
Example 3 is the fixed Dockerfile. Its last line is the exec-form answer to the fourth mistake.
Example 3 · The fixed Dockerfile
Runs in: a terminal with Docker installed
# syntax=docker/dockerfile:1FROM eclipse-temurin:25-jdk AS buildWORKDIR /workspaceCOPY mvnw pom.xml ./COPY .mvn .mvnRUN chmod +x mvnw && ./mvnw -B dependency:go-offlineCOPY src srcRUN ./mvnw -B package -DskipTestsFROM eclipse-temurin:25-jreRUN groupadd --system spring && useradd --system --gid spring --no-create-home springWORKDIR /appCOPY --from=build /workspace/target/*.jar app.jarUSER spring:springEXPOSE 8080ENTRYPOINT ["java", "-jar", "/app/app.jar"]REPOSITORY TAG IMAGE ID CREATED SIZE shoplite-api 1.2.0 a83f6c21d4e9 14 seconds ago 331MB spring
What this code does
- Pinned tags, a JDK only in the
buildstage,pom.xmlbeforesrc, aspringuser and an exec-formENTRYPOINT: one fix per mistake. - Add a
.dockerignore(from the earlier lesson) so the context stays small. The project lesson goes further with a Maven cache mount and Spring Boot layers.
Only PID 1 receives SIGTERM from docker stop. With the shell form java may never hear it, Spring cannot shut down gracefully, and Docker kills it after 10 seconds (exit 137). The exec form starts java directly. Prefer ENTRYPOINT for the fixed command, so docker run image --some.flag only adds arguments.
Example 4 · A tiny Dockerfile linter
import java.util.ArrayList;import java.util.List;
public class DockerfileLinter { static List<String> review(List<String> lines) { List<String> problems = new ArrayList<>(); String lastFrom = ""; boolean copiedEverything = false; boolean hasUser = false; for (int i = 0; i < lines.size(); i++) { String line = lines.get(i).trim(); int no = i + 1; if (line.startsWith("FROM ")) { lastFrom = line; String image = line.split("\\s+")[1]; if (!image.contains(":") || image.endsWith(":latest")) { problems.add("line " + no + ": pin a version tag instead of latest"); } } else if (line.equals("COPY . .")) { copiedEverything = true; } else if (line.startsWith("RUN") && line.contains("dependency:go-offline") && copiedEverything) { problems.add("line " + no + ": copy pom.xml before the source, or every change downloads all dependencies"); } else if (line.startsWith("USER ")) { hasUser = !line.endsWith(" root"); } else if ((line.startsWith("CMD ") || line.startsWith("ENTRYPOINT ")) && !line.contains("[")) { problems.add("line " + no + ": use exec form [\"java\", ...] so java receives SIGTERM"); } } if (!lastFrom.contains("-jre")) { problems.add("final stage: run on a JRE image, not a JDK"); } if (!hasUser) { problems.add("final stage: no USER line, the app runs as root"); } return problems; }
public static void main(String[] args) { List<String> bad = List.of( "FROM eclipse-temurin:latest", "WORKDIR /app", "COPY . .", "RUN ./mvnw -B dependency:go-offline", "RUN ./mvnw -B package -DskipTests", "CMD java -jar target/shoplite-api-1.2.0.jar");
List<String> problems = review(bad); problems.forEach(System.out::println); System.out.println(problems.size() + " problems found"); }}line 1: pin a version tag instead of latest line 4: copy pom.xml before the source, or every change downloads all dependencies line 6: use exec form ["java", ...] so java receives SIGTERM final stage: run on a JRE image, not a JDK final stage: no USER line, the app runs as root 5 problems found
What this code does
- The linter reads the bad Dockerfile line by line and reports all five mistakes: the tag, the cache order, the shell form, the JDK final stage and the missing
USER. - Real tools such as Hadolint check many more rules in the same way; running one in CI keeps these mistakes from coming back.
Finish up
Mark complete & continue
Next: Project: a production Dockerfile for shoplite-api