Skip to content

Grokem · https://www.grokem.com/programming/application-development/spring-boot-docker-image-buildpacks-or-layered-jars-built-and-verified

Application DevelopmentTutorialIntermediate level

Spring Boot Docker Image: Buildpacks or Layered Jars, Built and Verified

Build a Spring Boot container image with Cloud Native Buildpacks and no Dockerfile, then check the layer index that lets Docker reuse cached layers. Every step ends in a command you can run and an output you can check.

Krishna Sharma

Technical Writer

Published
  • 30 min to complete
  • 0 sec

Tested with
  • Spring Boot
  • Gradle
  • Spring Boot Gradle plugin (bootBuildImage, bootJar)
  • Spring Boot Maven plugin (build-image goal)
  • Cloud Native Buildpacks (Paketo)
  • Docker Engine
Your progress
  1. Spring Boot Docker Image: Buildpacks or Layered Jars, Built and Verified9 min(finished)
    0%

Before you start

5
  • A working Spring Boot application built with Gradle or Maven, with the Spring Boot plugin applied
  • A Docker daemon running on your machine, reachable from the Docker CLI
  • The Spring Boot Actuator dependency in the application if you want to run the health check in step 5
  • curl and jq on your path for the health check
  • Optional: the pack CLI, only for the Paketo route in step 7

You can copy a Spring Boot uber jar into a Docker image and run it, but the official Spring Boot documentation names two downsides. Running an uber jar without unpacking it carries overhead that can be noticeable in a container. And putting your code and all its dependencies in one layer is not optimal.

You probably recompile your code more often than you upgrade Spring Boot. If jar files sit in a layer before your application classes, Docker often needs to rebuild only the bottom layer and picks the rest from its cache.

This tutorial gives you two ways to get there:

  • Cloud Native Buildpacks (CNB). The Gradle task bootBuildImage (and the Maven build-image goal) builds an OCI image from your project with no Dockerfile. Paketo's pack CLI does the same from the command line.
  • Layered jars. Spring Boot can add a layer index file, layers.idx, to the jar. It lists the layers and the parts of the jar that go in each one, so tooling can build cache-friendly images.

The main path uses Gradle commands, because the Gradle plugin pages give the task names. The layered jar part stops at the index itself, because the pages used for this guide do not show the Dockerfile commands that consume it. Step 9 points you to the right pages.

All version numbers are left out on purpose. Check the version of Spring Boot, the plugin and the builder your project uses, and open the matching documentation page.

Step 1 of 11: Choose between buildpacks and a layered jar

Decide which route fits before you type anything.

  • Pick buildpacks when you want a finished image with no Dockerfile. The builder inspects the application and its buildpacks shape the image. For Java, the Paketo Java Buildpack installs a JRE (only the JRE reaches the final image, the JDK stays in the build container) and, for Spring Boot apps, adds Boot-specific optimisations and image labels.
  • Pick a layered jar when you already own a Dockerfile pipeline and want to control every layer yourself.

Why: the two routes solve the same caching problem differently. Buildpacks hide it, layered jars expose it.

Step 2 of 11: Confirm that the Docker daemon is reachable

Run a command that talks to the daemon.

bootBuildImage requires access to a Docker daemon. It reads your local Docker CLI configuration to find the current context and uses that connection. If it cannot determine a context, it falls back to a default local connection, which works with Docker Engine on all supported platforms without configuration.

Why: a daemon problem is the most common reason an image build fails, and it is quicker to find with docker info than inside a Gradle stack trace.

bash
docker info

Step 3 of 11: Check that the Spring Boot plugin is applied

Open your build file and confirm the Spring Boot plugin is there.

With Gradle, the bootBuildImage task is created automatically when the java or war plugin is applied, so a normal Spring Boot Gradle project already has it. With Maven, the plugin is declared in the plugins section of pom.xml, as in the plugin's Getting Started page:

Why: the image tasks belong to the Spring Boot plugin. Without it there is nothing to build the image from.

xml
<project>
  <modelVersion>4.0.0</modelVersion>
  <artifactId>getting-started</artifactId>
  <!-- ... -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

Step 4 of 11: Build the image with bootBuildImage

From the project root, run the Gradle task.

The plugin invokes a builder that orchestrates the image generation. The builder bundles several buildpacks that inspect your application and influence the result. By default the plugin chooses the builder image, and it deduces the name of the generated image from your project properties.

For Maven, use the plugin's build-image goal. The Maven page used for this guide lists the goal but the exact command line is not reproduced here, so check the Spring Boot Maven plugin documentation for your version.

Why: one task compiles, packages and builds the image, so you do not maintain a Dockerfile for the default case.

bash
./gradlew bootBuildImage

Step 5 of 11: List the image and run it

List local images to find the name the plugin generated, then run it. Replace YOUR_IMAGE_NAME with the repository name shown in the list.

If your application exposes the Actuator health endpoint, call it from a second terminal. A healthy Paketo sample image returns {"status":"UP"} from that endpoint.

Why: a running container that answers a request proves the image is complete, not just that the build finished.

bash
docker images
bash
docker run --rm --tty --publish 8080:8080 YOUR_IMAGE_NAME
bash
curl -s http://localhost:8080/actuator/health | jq .

Step 6 of 11: Inspect the labels on the image

Print the image labels.

For Spring Boot applications the Spring Boot Buildpack adds metadata to the image config. Among its labels, org.opencontainers.image.title is set from Implementation-Title in MANIFEST.MF, and org.opencontainers.image.version from Implementation-Version. It also adds org.springframework.boot.version.

Why: labels tell you later which application and Boot version a given image contains, which matters when several images are in a registry.

bash
docker image inspect --format '{{json .Config.Labels}}' YOUR_IMAGE_NAME | jq .

Step 7 of 11: Build the same way with the pack CLI

Use this route when you do not want a Spring Boot plugin in the build, or to try the Paketo sample applications. Set the Paketo Base builder as the default, clone the samples and build the Maven sample.

The correct build tool (Maven, Gradle, Leiningen or sbt) is detected from the application directory. After the build, the buildpack replaces your source with the exploded archive.

Then run it and call the health endpoint as in step 5, using samples/java as the image name.

Why: pack is another Cloud Native Buildpacks platform, so you get the same kind of image without the Gradle or Maven plugin.

bash
pack config default-builder paketobuildpacks/builder-jammy-base
git clone https://github.com/paketo-buildpacks/samples
cd samples
pack build samples/java --path java/maven
bash
docker run --rm --tty --publish 8080:8080 samples/java

Step 8 of 11: Set a container memory limit and watch the heap follow

Run the image with a memory limit. Use any value your application can live with; 768m below is only an example.

The Paketo Java Buildpack includes the Java Memory Calculator. It computes the heap as total container memory minus non-heap minus headroom (headroom defaults to 0). It then appends the resulting JVM flags to JAVA_TOOL_OPTIONS when the image runs. The Paketo reference advises against setting -Xmx directly, because the non-heap value stays fixed for a given application and a hand-set heap can then be too large or too small.

Why: with a limit set, the calculator has a real number to work from. A lower limit gives a smaller heap, a higher one gives all the extra memory to the heap.

bash
docker run --rm --tty --publish 8080:8080 --memory 768m YOUR_IMAGE_NAME

Step 9 of 11: Build the jar and confirm the layer index

Build the executable jar with bootJar, then look inside it for layers.idx. The assemble and build tasks run bootJar for you.

By default the jar task uses the classifier plain, so build/libs holds both the executable jar and a plain jar. Use the one without the plain classifier.

If the grep prints nothing, your jar has no layer index. The Gradle plugin's section on packaging layered jars explains how to add one, and the Maven plugin has an equivalent section. Those pages are the reference for the exact configuration.

Why: the layer index is the input that tooling uses to separate rarely changing code from frequently changing code.

bash
./gradlew bootJar
ls build/libs
unzip -l build/libs/YOUR_APP.jar | grep layers.idx

Step 10 of 11: Read the layers in order

The index lists layers in the order they should be added to the Docker or OCI image. Out of the box, Spring Boot supports four:

  1. dependencies: regular released dependencies.
  2. spring-boot-loader: everything under org/springframework/boot/loader.
  3. snapshot-dependencies: snapshot dependencies.
  4. application: your classes and resources.
layers.idx orderapplication4snapshot-dependencies3spring-boot-loader2dependencies1changes on every buildchanges rarely,reused from cache
The layer order from layers.idx puts stable libraries first and your code last.

The order is deliberate. Library code changes less between builds than yours, so it goes first and stays cached. Your code goes last, so a rebuild usually changes only the bottom layer.

The pages used for this guide do not show how to extract these layers or write the Dockerfile that copies them. For that, follow the Efficient Container Images page and the packaging layered jar sections of the Gradle and Maven plugin documentation.

Why: understanding the order tells you why a code-only change should not re-download or re-push the dependency layers.

Step 11 of 11: Rebuild after a code-only change and compare

Change one line of application code, rebuild, and watch how much work is repeated.

With the image build, look at the build log for layers reported as reused. With a Dockerfile built from the layer index, Docker output marks unchanged layers as cached. The exact wording of the output depends on your Docker version and builder, so look for the dependency layers being reused rather than for specific text.

Why: this is the practical payoff of layering, and you only know it works for your project when you see the dependency layers skipped.

bash
./gradlew bootBuildImage

Expected result

After step 4, `docker images` lists a new image whose name is derived from your project. After step 5, the container starts and, if Actuator is present, the health call prints: { "status": "UP" } After step 6, the labels include `org.opencontainers.image.title`, `org.opencontainers.image.version` and `org.springframework.boot.version`. After step 9, `unzip -l` prints a line containing `layers.idx`. The index lists the layers `dependencies`, `spring-boot-loader`, `snapshot-dependencies` and `application`, in that order.

Troubleshooting

ProblemLikely causeFix
bootBuildImage fails because it cannot connect to DockerThe Docker daemon is not running, or the Docker CLI context points at a different host.Run docker info. If it fails, start Docker. To point the task elsewhere, set DOCKER_HOST, DOCKER_CONTEXT, DOCKER_CONFIG, and for HTTPS DOCKER_TLS_VERIFY and DOCKER_CERT_PATH, or use the docker properties in the plugin configuration.
The build cannot pull the builder or run image from a private registryThe registry needs authentication and no credentials were supplied.Provide credentials with the docker.builderRegistry properties (user authentication or identity token). Use docker.publishRegistry when publishing the generated image. Without them, the plugin reads your existing Docker configuration file.
The health call is refused or returns an errorThe container is still starting, the port is not published, or the application does not include Actuator.Check the container logs, confirm the run command includes --publish 8080:8080, and add the Actuator dependency if you want /actuator/health.
build/libs contains two jars and you picked the wrong oneWhen bootJar is configured, the jar task uses the classifier plain, so both archives are built.Use the jar without the plain classifier. To change this, set archiveClassifier on the bootJar and jar tasks, or disable the jar task. Do not disable it when creating native images.
grep finds no layers.idx in the jarThe jar was built without a layer index.Follow the packaging layered jar or war section of the Gradle or Maven plugin documentation to add the index, then rebuild.
The application runs out of memory or has a surprisingly small heapThe Java Memory Calculator derives the heap from the container memory limit, and -Xmx set by hand can conflict with the fixed non-heap value.Adjust the container memory limit instead of setting -Xmx. For explicit overrides, see the Paketo section on configuring the JVM at runtime.

Frequently asked questions

Do I need a Dockerfile to build a Spring Boot image?

No. The bootBuildImage Gradle task and the Maven build-image goal use Cloud Native Buildpacks to create an OCI image from your project. The pack CLI with a Paketo builder works too.

Why not just copy the uber jar into an image?

It works, but running an uber jar without unpacking it adds overhead, and one layer for code and dependencies defeats caching. Separating them lets Docker reuse the dependency layers.

Which layers does Spring Boot support?

By default: dependencies, spring-boot-loader, snapshot-dependencies and application, listed in that order in layers.idx.

Does the image run as root?

No. For security reasons, images built with the plugin build and run as non-root users. The CNB specification has the details.

How does the image decide its JVM heap size?

The Paketo Java Memory Calculator subtracts non-heap memory and headroom from the container memory limit and passes the result as -Xmx through JAVA_TOOL_OPTIONS. Change the container limit rather than setting -Xmx.

How do I build against a remote Docker daemon?

Set DOCKER_HOST, or use DOCKER_CONTEXT, DOCKER_CONFIG, DOCKER_TLS_VERIFY and DOCKER_CERT_PATH. The same settings are available as docker properties in the plugin configuration.

Next steps

  • Add a layer index to your jar and build a Dockerfile image from it, following the Efficient Container Images page.
  • Configure the builder, run image and image name through the bootBuildImage task properties.
  • Publish the generated image with the docker.publishRegistry properties.
  • Tune the JVM at runtime using the Paketo how-to on configuring the JVM.

References

From Grokem: https://www.grokem.com/programming/application-development/spring-boot-docker-image-buildpacks-or-layered-jars-built-and-verified

Finished this article?

How did this strike you?

Be the first to react – it is anonymous.

Community

Questions about this?

Ask in Questions and help and get help from other readers.

Ask a questionBrowse Questions and help

Comments

No comments yet. Share what worked for you, or ask a question.

Keep learning

Picked for this article

Related reading, discussions and learning paths on the same subject.

All in Application Development

Learning paths

Learning pathBeginner

Infrastructure basics for data work

The ground a data project stands on: the command line, how a name finds a server, packaging an app in a container, where files and databases live, keeping secrets out of code, backups you have tested and a cloud bill you control.

7 lessonsabout 15 minStart

Learning pathIntermediate

Data pipelines you can trust

How data gets from source to report without surprises: the ETL and ELT choice, a first pipeline, cleaning, quality checks, safe re-runs and scheduling.

7 lessonsabout 75 minStart

Choose what we may use. You can change this at any time with “Privacy choices” at the foot of every page. Details are in the Cookie policy and the Privacy policy.

Strictly necessary

Remembers your theme, the lessons you marked as done and this choice. It stays on your device, tracks nothing and cannot be switched off.

Always on
What exactly is collected, and why

Google Analytics

Collects
The pages you view, your device and browser type, your language, how you reached the site and your approximate location (country and city, worked out from your IP address).
Why
To understand which pages and lessons are used, so we can improve them.
Stored
Two cookies, _ga and _ga_<id>, for up to 2 years. Google acts for us; the data is processed by Google, including outside your country.

Grokem’s own counts

Collects
The pages you open and how long you stay, how far you scroll, where you came from, your device type, browser, screen size, language and time zone. Your IP address is turned into a code that changes every day; it is never stored as it is.
Why
To see how long lessons are read and where readers leave. Not shared with anyone.
Stored
A random visitor ID, a visit ID and the time of your last page view in your browser’s storage (gr_vid, gr_sid, gr_last). No name or email is attached.