Docker for Kubernetes · Reference

Dockerfile cheat sheet

This sheet grows with each lesson. The full semantics are in the Dockerfile reference.

The minimal Java service

FROM eclipse-temurin:21-jdk    # base image; -jdk has javac, -jre only runs Java
WORKDIR /app                   # created if missing; later paths are relative to it
COPY App.java .                # from the build context into /app
RUN javac App.java             # runs at build time, saved as a layer
EXPOSE 8080                    # documentation only
CMD ["java", "App"]            # default command at run time, exec form

The multi-stage Java service (Maven)

FROM maven:3.9-eclipse-temurin-21 AS build   # stage 1: has Maven and the JDK
WORKDIR /app
COPY pom.xml .                               # alone, so code edits don't touch it
RUN mvn -B dependency:go-offline             # expensive, cached until pom.xml changes
COPY src ./src                               # changes often, so it comes late
RUN mvn -B package                           # writes /app/target/app.jar

FROM eclipse-temurin:21-jre                  # stage 2, the image you ship: no compiler
WORKDIR /app                                 # each stage starts fresh; set it again
COPY --from=build /app/target/app.jar .      # take only the jar
EXPOSE 8080
CMD ["java", "-jar", "app.jar"]

Next to it, a .dockerignore containing target/ and .git. In testing, the single-stage Maven image was 590 MB and this one 341 MB, nearly all of it the shared JRE base.

The build cache

Instructions

InstructionHappens atRemember
FROMBuildMust be first. Pin a tag, such as 21-jdk. Each FROM starts a new stage; AS name names it. The image is the last stage.
WORKDIRBuildUse it instead of RUN cd …. Also the container's working directory.
COPYBuildSources are relative to the build context, never outside it. COPY --from=build /path . copies from an earlier stage instead.
RUNBuildMust finish. Never start the service here.
EXPOSERecordedDoesn't publish. Use docker run -p.
CMDRunOnly the last one counts. Replaces the base image's CMD. Overridden by a command after the image name in docker run, or by args in Kubernetes.

Exec form vs shell form

Exec formShell form
WrittenCMD ["java", "App"]CMD java App
Actually runsjava App/bin/sh -c "java App"
PID 1JavaThe shell
docker stopJava gets SIGTERM, exits fast: Exited (143)Signal ignored, killed after 10 s: Exited (137)
Use forCMD, alwaysRUN, where shell features like && help

Exit codes above 128 mean "killed by a signal": 128 + 15 (SIGTERM) = 143; 128 + 9 (SIGKILL) = 137.

Common mistakes

Related ideas