Sub topic 9
Packaging a Container Image with a Dockerfile
This chapter shows how to turn the executable JAR into a container image with a Dockerfile. It covers the minimal image, layered JARs for faster rebuilds, multi-stage builds, and the errors that most often appear.
Prerequisites
This chapter assumes you can:
- Build an executable JAR with
./mvnw clean packageor./gradlew clean bootJar, as covered earlier in this tutorial. - Run a JAR with
java -jarand pass configuration through environment variables. - Use Docker or a compatible tool (Podman, Buildah) from the command line.
What a container image gives you
A container image is a read-only package that holds a filesystem and the default command to run. A container is a running instance of that image. The image carries the JRE, your JAR, and nothing else you did not add. The same image runs on a laptop, a CI runner, and a Kubernetes node.
The image is the unit of deployment. Configuration and secrets stay outside it, as the chapters on externalized configuration and secrets describe. You supply them when you start the container.
A minimal Dockerfile
This Dockerfile copies the built JAR onto a JRE base image and runs it as a non-root user.
FROM eclipse-temurin:21-jre
RUN useradd --system spring
USER spring
WORKDIR /app
COPY target/myapp-1.0.0.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]Each instruction does one job:
| Instruction | Purpose |
|---|---|
| `FROM` | Chooses the base image. A JRE image is smaller than a JDK image because it has no compiler. |
| `RUN useradd --system spring` | Creates an unprivileged account at build time. |
| `USER spring` | Makes later instructions and the running process use that account. |
| `WORKDIR /app` | Sets the working directory and creates it if needed. |
| `COPY` | Copies the JAR from the build context into the image. |
| `EXPOSE 8080` | Documents the port. It does not publish it. |
| `ENTRYPOINT` | Defines the command that starts the application. |
Build and run it:
./mvnw clean package
docker build -t myorg/myapp:1.0.0 .
docker run --rm -p 8080:8080 \
-e DB_URL=jdbc:postgresql://db:5432/app \
-e DB_PASSWORD=change-me \
myorg/myapp:1.0.0The -p 8080:8080 flag publishes the container port on the host. Without it, EXPOSE alone leaves the port unreachable from outside. The -e flags feed the ${DB_URL} and ${DB_PASSWORD} placeholders in application.properties.
Why the exec form of ENTRYPOINT matters
The JSON array form (["java", "-jar", "app.jar"]) starts Java directly as process 1 in the container. When Docker or Kubernetes sends SIGTERM, the JVM receives it and Spring Boot runs its graceful shutdown. The shell form (ENTRYPOINT java -jar app.jar) wraps the command in /bin/sh -c. The shell may not forward the signal, so the application can be killed after the timeout without draining requests.
Why a single fat JAR layer is wasteful
An image is a stack of layers. Docker caches each layer and reuses it when the instruction and its inputs are unchanged. In the minimal Dockerfile, the whole JAR is one layer. A fat JAR (an executable JAR that bundles all dependencies) is often 30 to 100 MB, and nearly all of it is third-party libraries that rarely change. A one-line code change produces a new JAR, so the entire layer is rebuilt, pushed to the registry, and pulled by every node.
Layered JARs
Spring Boot executable JARs include a layer index, BOOT-INF/layers.idx. It groups the JAR's contents so you can split them into separate image layers, ordered from least to most likely to change:
| Layer | Contents |
|---|---|
| `dependencies` | Release versions of third-party libraries |
| `spring-boot-loader` | The Spring Boot loader classes |
| `snapshot-dependencies` | Snapshot versions of libraries |
| `application` | Your classes and resources |
You can list the layers in a built JAR:
java -Djarmode=tools -jar target/myapp-1.0.0.jar list-layersExtract them into directories named after the layers:
java -Djarmode=tools -jar target/myapp-1.0.0.jar extract --layers --destination extractedThe tools jar mode is available in Spring Boot 3.3 and later. Earlier 3.x versions use -Djarmode=layertools with extract and no --destination option. Check the version your project uses.
A multi-stage Dockerfile with layers
A multi-stage build uses more than one FROM. An early stage does the work (here, extracting layers), and the final stage copies only what it needs. Nothing from the earlier stages ends up in the final image unless you copy it.
FROM eclipse-temurin:21-jre AS builder
WORKDIR /builder
COPY target/myapp-1.0.0.jar application.jar
RUN java -Djarmode=tools -jar application.jar extract --layers --destination extracted
FROM eclipse-temurin:21-jre
RUN useradd --system spring
USER spring
WORKDIR /app
COPY --from=builder /builder/extracted/dependencies/ ./
COPY --from=builder /builder/extracted/spring-boot-loader/ ./
COPY --from=builder /builder/extracted/snapshot-dependencies/ ./
COPY --from=builder /builder/extracted/application/ ./
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "application.jar"]With Spring Boot 3.3 and later, the extract command with the tools mode also writes a small application.jar launcher that references the extracted libraries, so java -jar application.jar works from the extracted layout. The order of the COPY lines matters. Docker reuses every layer up to the first one that changed, so the stable dependencies layer goes first and application goes last.
After a code-only change, only the application layer is rebuilt and transferred. This is typically a few hundred kilobytes instead of tens of megabytes.
Building the JAR inside Docker
The previous examples copy a JAR that you built on the host. This works well in CI, where one job builds and tests the JAR and a later job packages it. If you want Docker to do the compile as well, add a JDK build stage:
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw -q dependency:go-offline
COPY src src
RUN ./mvnw -q clean package -DskipTests
FROM eclipse-temurin:21-jre
RUN useradd --system spring
USER spring
WORKDIR /app
COPY --from=build /src/target/myapp-1.0.0.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]Copying pom.xml before src lets Docker cache the dependency download. The dependency layer is rebuilt only when pom.xml changes. The -DskipTests flag keeps the image build fast, so run tests as a separate step in your pipeline.
Keeping the build context small
docker build . sends the whole directory, called the build context, to the builder. A .dockerignore file excludes paths from it:
.git
.idea
*.iml
target/classes
build
.gradle
*.log
.envExcluding .env and similar files also keeps local secrets from being copied into an image by an accidental COPY . ..
If your Dockerfile copies target/myapp-1.0.0.jar, do not ignore all of target. Otherwise the COPY fails.
Image design choices
| Choice | Trade-off |
|---|---|
| JRE image vs. JDK image | JRE is smaller and has a smaller attack surface. A JDK image includes tools such as `jcmd` for debugging. |
| Debian/Ubuntu base vs. Alpine | Alpine is smaller but uses musl libc. Some native libraries behave differently on musl. Debian-based images are the safer default. |
| Pinned tag vs. `latest` | A pinned tag such as `21-jre` or a digest gives repeatable builds. `latest` can change under you. |
| Version tag vs. `latest` for your own image | Use a version or commit SHA so each deployment is traceable and rollbacks are exact. |
Common errors
no main manifest attribute, in app.jar. You copied a plain JAR, not the repackaged one. Check that the Spring Boot plugin ran, and for Gradle use thebootJaroutput. For Gradle builds, a-plain.jarfile next to the boot JAR is the unpackaged one.COPY failed: no source files were specified. The path does not exist in the build context. Check the JAR name against the<version>in your build file, or use a wildcard such astarget/*.jarwhen only one JAR is present.- Port not reachable. The app listens on 8080 in the container, but you did not publish it with
-p. Also check that the app binds to all interfaces, which is the Spring Boot default. UnsupportedClassVersionError. The JAR was compiled with a newer Java than the image runs. Match the base image version to thejava.versionof the project.- Permission denied when writing files. The non-root user cannot write to the directory. Create the directory and change its owner in the Dockerfile, or mount a volume with suitable permissions.
- The container stops after 10 seconds without draining requests. The process is not receiving SIGTERM. Check for the shell form of
ENTRYPOINT.
Scanning and tagging
Publish images with an immutable tag, such as the Git commit SHA or the release version. Scan them in CI with a tool such as Trivy or Grype to catch known vulnerabilities in the base image and in the libraries inside the JAR. Rebuild regularly so base image security patches reach production even when your code has not changed.
Exercise
Your team's image takes several minutes to push after every small code change, even though only one class changed. The Dockerfile has COPY target/myapp-1.0.0.jar app.jar. What change reduces the transfer size, and why does the order of the layers matter?
Show answer
Extract the JAR into layers with java -Djarmode=tools -jar app.jar extract --layers in a builder stage, then copy each layer with its own COPY --from=builder line in the final stage. Docker caches layers and reuses all layers up to the first changed one. Putting dependencies, spring-boot-loader, and snapshot-dependencies first and application last means a code change rebuilds and pushes only the small application layer.
Exercise
A container running your application takes the full 30-second timeout to stop, and in-flight requests fail, even though server.shutdown=graceful is set. The Dockerfile ends with ENTRYPOINT java -jar app.jar. What is wrong, and what is the fix?
Show answer
This is the shell form, so /bin/sh -c runs as process 1 and may not forward SIGTERM to the JVM. Spring Boot never starts its graceful shutdown. Change it to the exec form, ENTRYPOINT ["java", "-jar", "app.jar"], so the JVM receives the signal directly.