Building Java container images: Dockerfile, Jib and Buildpacks compared
There are three common ways to turn a Java application into a container image: write a Dockerfile, let Jib assemble the image from your build's outputs, or let Cloud Native Buildpacks decide everything. This page uses jib-core, the library behind the Jib plugins, to build an image straight to a tar file with no Docker daemon. It then opens the tar to show what is inside, tests whether the build is reproducible, and compares the result with what a Dockerfile and Buildpacks produce.
Contents
Three ways to build an image
A container image is not a special file format. It is a set of compressed tar files, the layers, plus two small JSON documents. A config holds the entrypoint, environment, user and the order of the layers, and a manifest lists the config and layers by their SHA-256 digests (in a tar file for docker loadmanifest.json
- Dockerfile: you write the steps, and a build engine such as Docker's BuildKit, Buildah or Podman runs them one by one, usually inside containers. Each
orCOPY that changes files becomes a layer.RUN - Jib: a Java library from Google, with Maven and Gradle plugins, that builds the image from your build's dependency JARs, resources and compiled classes. It writes the layers and JSON files itself and sends the image to a registry, a Docker daemon or a tar file, without running any container.
- Cloud Native Buildpacks: a buildpack detects one kind of application and adds what it needs, such as a JVM. A builder image bundles buildpacks and assembles the image with no instructions from you. Spring Boot's Maven goal
and its Gradle taskspring-boot:build-image use the Java buildpacks of Paketo, an open-source buildpacks project.bootBuildImage
| Dockerfile | Jib | Buildpacks (Spring Boot) | |
|---|---|---|---|
| Configured in | Dockerfile | pom.xmlbuild.gradle | pom.xmlbuild.gradle |
| Needs a Docker daemon | Yes, unless you use a daemonless builder such as Buildah or Podman | No, except to load into a local daemon | Yes, or a compatible engine such as Podman |
| Default base image | Whatever FROM | The eclipse-temurin<from> | Chosen by the builder (Ubuntu Noble-based for the default builder-noble-java-tiny |
| Layers | One per instruction that changes files | Dependencies, snapshot dependencies, project dependencies, resources, classes | JRE, helpers such as the memory calculator, and the slices listed in Spring Boot's layer index, BOOT-INF/layers.idx |
jlink
Building an image with Jib, no Docker required
The Jib plugins are thin wrappers around jib-corespring-boot-starter-webmvcmvn jib:buildTarjib-core
Docker Hub and the other registries could not be reached from the machine these examples ran on, so the base image could not be eclipse-temurin:21-jrejlinkscratchJavaContainerBuilder
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.spi.ToolProvider;
import java.util.zip.GZIPInputStream;
import javax.tools.JavaCompiler;
import com.google.cloud.tools.jib.api.Containerizer;
import com.google.cloud.tools.jib.api.JavaContainerBuilder;
import com.google.cloud.tools.jib.api.Jib;
import com.google.cloud.tools.jib.api.JibContainer;
import com.google.cloud.tools.jib.api.TarImage;
import com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath;
import com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer;
import com.google.cloud.tools.jib.api.buildplan.FilePermissions;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
public class JibToTar {
public static void main(String[] args) throws Exception {
Path work = Files.createTempDirectory("jib-demo");
String appClasspath = System.getProperty("app.classpath");
List<Path> dependencies = Arrays.stream(appClasspath.split(":")).map(Path::of).toList();
// The application: one Spring Boot class and one resource, compiled here
Path source = work.resolve("src/demo/App.java");
Files.createDirectories(source.getParent());
Files.writeString(source, """
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
""");
Path classes = Files.createDirectories(work.resolve("classes"));
JavaCompiler javac = javax.tools.ToolProvider.getSystemJavaCompiler();
javac.run(null, null, null, "-d", classes.toString(), "-cp", appClasspath,
source.toString());
Path resources = Files.createDirectories(work.resolve("resources"));
Files.writeString(resources.resolve("application.properties"), "server.port=8080\n");
// The base image: no registry is reachable here, so put a jlink runtime on an
// empty image and save it as a tar file, the same way as the application image
Path jre = work.resolve("jre");
ToolProvider.findFirst("jlink").orElseThrow().run(System.out, System.err,
"--add-modules", "java.se,jdk.unsupported,jdk.crypto.ec", "--strip-debug",
"--no-man-pages", "--no-header-files", "--output", jre.toString());
Path baseTar = work.resolve("jre-base.tar");
Jib.fromScratch()
.addFileEntriesLayer(FileEntriesLayer.builder().setName("jre")
.addEntryRecursive(jre, AbsoluteUnixPath.get("/opt/java"),
(file, target) -> Files.isDirectory(file)
|| Files.isExecutable(file)
? FilePermissions.fromOctalString("755")
: FilePermissions.DEFAULT_FILE_PERMISSIONS)
.build())
.addEnvironmentVariable("JAVA_HOME", "/opt/java")
.addEnvironmentVariable("PATH", "/opt/java/bin:/usr/bin:/bin")
.containerize(Containerizer.to(TarImage.at(baseTar).named("local/jre-base:21"))
.setBaseImageLayersCache(work.resolve("cache/base"))
.setApplicationLayersCache(work.resolve("cache/app")));
// The application image, built the way the Jib Maven and Gradle plugins build one
Path appTar = work.resolve("payment-service.tar");
JibContainer image = JavaContainerBuilder
.from(TarImage.at(baseTar).named("local/jre-base:21"))
.addDependencies(dependencies)
.addResources(resources)
.addClasses(classes)
.addJvmFlags("-XX:MaxRAMPercentage=75")
.setMainClass("demo.App")
.toContainerBuilder()
.setUser("10001:10001")
.containerize(Containerizer.to(TarImage.at(appTar).named("payment-service:1.0"))
.setBaseImageLayersCache(work.resolve("cache/base"))
.setApplicationLayersCache(work.resolve("cache/app")));
System.out.println("Image ID: " + image.getImageId());
System.out.printf("%s: %.1f MB%n%n", appTar.getFileName(), Files.size(appTar) / 1e6);
Map<String, byte[]> files = readTar(Files.newInputStream(appTar));
System.out.println("Entries in the tar file:");
files.forEach((name, data) -> System.out.printf(" %-40s %,12d bytes%n",
shorten(name), data.length));
JsonObject manifest = JsonParser.parseString(text(files.get("manifest.json")))
.getAsJsonArray().get(0).getAsJsonObject();
System.out.println("\nmanifest.json: RepoTags " + manifest.get("RepoTags")
+ ", Config " + shorten(manifest.get("Config").getAsString()));
JsonObject config = JsonParser.parseString(
text(files.get(manifest.get("Config").getAsString()))).getAsJsonObject();
JsonObject runConfig = config.getAsJsonObject("config");
System.out.println("\nImage config:");
System.out.println(" created " + config.get("created").getAsString());
System.out.println(" os/arch " + config.get("os").getAsString() + "/"
+ config.get("architecture").getAsString());
System.out.println(" User " + runConfig.get("User").getAsString());
System.out.println(" Env " + runConfig.get("Env"));
System.out.println(" Entrypoint " + runConfig.get("Entrypoint"));
System.out.println("\nLayers, in order:");
JsonArray history = config.getAsJsonArray("history");
int i = 0;
for (JsonElement layer : manifest.getAsJsonArray("Layers")) {
byte[] gz = files.get(layer.getAsString());
Map<String, TarArchiveEntry> entries = new LinkedHashMap<>();
try (TarArchiveInputStream tar = new TarArchiveInputStream(
new GZIPInputStream(new java.io.ByteArrayInputStream(gz)))) {
for (TarArchiveEntry e; (e = tar.getNextEntry()) != null; ) {
entries.put(e.getName(), e);
}
}
long fileCount = entries.values().stream().filter(e -> !e.isDirectory()).count();
// Show the java launcher if the layer has one, otherwise the layer's last file
TarArchiveEntry sample = entries.getOrDefault("opt/java/bin/java", entries.values()
.stream().filter(e -> !e.isDirectory()).reduce((a, b) -> b).orElseThrow());
System.out.printf("%d. %-12s %,11d bytes gzipped, %3d %-6s e.g. %s%n", i + 1,
history.get(i).getAsJsonObject().get("comment").getAsString(),
gz.length, fileCount, fileCount == 1 ? "file," : "files,",
sample.getName());
System.out.printf(" mode %o, owner %d:%d, modified %s%n", sample.getMode(),
sample.getLongUserId(), sample.getLongGroupId(),
sample.getModTime().toInstant());
i++;
}
try (var paths = Files.walk(work)) {
paths.sorted(java.util.Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
}
}
static Map<String, byte[]> readTar(InputStream in) throws IOException {
Map<String, byte[]> files = new LinkedHashMap<>();
try (TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
for (TarArchiveEntry e; (e = tar.getNextEntry()) != null; ) {
files.put(e.getName(), tar.readAllBytes());
}
}
return files;
}
static String text(byte[] bytes) {
return new String(bytes, StandardCharsets.UTF_8);
}
// Layer file names are a 64-digit hash plus .tar.gz: keep the first 12 digits
static String shorten(String name) {
return name.replaceAll("([0-9a-f]{12})[0-9a-f]{52}", "$1...");
}
}
Image ID: sha256:8c8414321f0e2ed3496a12295e67bed028aaf3289ff4c7d85416e9f218e53950
payment-service.tar: 50.1 MB
Entries in the tar file:
f7199d20642c....tar.gz 30,408,667 bytes
0f7e024cc373....tar.gz 19,691,163 bytes
126c049cfe80....tar.gz 300 bytes
ffb24572b84a....tar.gz 649 bytes
config.json 1,072 bytes
manifest.json 368 bytes
manifest.json: RepoTags ["payment-service:1.0"], Config config.json
Image config:
created 1970-01-01T00:00:00Z
os/arch linux/amd64
User 10001:10001
Env ["PATH=/opt/java/bin:/usr/bin:/bin","JAVA_HOME=/opt/java"]
Entrypoint ["java","-XX:MaxRAMPercentage=75","-cp","/app/libs/*:/app/resources:/app/classes","demo.App"]
Layers, in order:
1. jre 30,408,667 bytes gzipped, 145 files, e.g. opt/java/bin/java
mode 100755, owner 0:0, modified 1970-01-01T00:00:01Z
2. dependencies 19,691,163 bytes gzipped, 41 files, e.g. app/libs/tomcat-embed-websocket-11.0.27.jar
mode 100644, owner 0:0, modified 1970-01-01T00:00:01Z
3. resources 300 bytes gzipped, 1 file, e.g. app/resources/application.properties
mode 100644, owner 0:0, modified 1970-01-01T00:00:01Z
4. classes 649 bytes gzipped, 1 file, e.g. app/classes/demo/App.class
mode 100644, owner 0:0, modified 1970-01-01T00:00:01Z
- The whole build, base image included, ran in one JVM: no Docker daemon, no
, no container started. That is why Jib fits CI runners where Docker is not available or not allowed.docker build - The tar holds four gzipped layers, named by the SHA-256 digest of their compressed bytes, plus
andconfig.json .manifest.json accepts this layout (not run here).docker load names the imagemanifest.json and points to the config and the layers in order. The image ID printed first is the digest ofpayment-service:1.0 .config.json
What Jib put in the image
The output shows what Jib did with the program's settings and what it chose by default:
- Entrypoint: Jib wrote
. There is no fat JAR in the image: Jib puts the dependency JARs and the resource and class directories on the classpath, so nothing has to unpack a JAR at startup. Thejava -XX:MaxRAMPercentage=75 -cp /app/libs/*:/app/resources:/app/classes demo.App command is found through thejava inherited from the base image.PATH - Layer order: the base image's
layer first, then dependencies (19.7 MB gzipped), resources (300 bytes) and classes (649 bytes). Parts that change least often come first, so a code change replaces only the last, smallest layer.jre - Timestamps: the image's
date is 1970-01-01, the Unix epoch, and every file is dated one second after it (created in the plugins' settings). Jib drops the real times on purpose, and that is what makes the build reproducible.EPOCH_PLUS_SECOND - Ownership and modes: files belong to root (0:0) with mode 644. The
launcher gets mode 755 because the program passed a permissions function for thejava layer. Root owns the files and only the owner may write them, so the non-root user can read the application but not change it.jre - User:
became the config'ssetUser("10001:10001") field, so the container does not run as root. A numeric user also passes Kubernetes'User check, which cannot verify a user name.runAsNonRoot - History: each layer has a
naming it (comment ,jre ,dependencies ,resources ), whichclasses shows in its COMMENT column. CREATED BY shows the Jib version where a Dockerfile build shows its instructions.docker history
The Maven and Gradle plugins follow the same layer plan, and also give SNAPSHOT dependencies and project dependencies (other modules of the same build) layers of their own. Jib 3.1 and later also writes /app/jib-classpath-file/app/jib-main-class-filejib-core
Reproducible builds: same input, same digest
A build is reproducible when the same source gives a byte-identical image, and therefore the same digest. It matters because registries, caches and security scanners identify images by digest. This program builds four images and prints the image ID and each layer's diff ID: the digest of the uncompressed layer, as listed in the config. Unlike the gzipped digest that named the files in the first program, it does not depend on gzip settings. Build b uses the same files as a, but with new modification times, as after a fresh checkout. Build c changes one property. Build d uses the content of a, but asks Jib to keep the real file times and the real build time:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import com.google.cloud.tools.jib.api.Containerizer;
import com.google.cloud.tools.jib.api.JavaContainerBuilder;
import com.google.cloud.tools.jib.api.JibContainerBuilder;
import com.google.cloud.tools.jib.api.TarImage;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
public class JibReproducible {
static Path work;
static List<Path> dependencies;
public static void main(String[] args) throws Exception {
work = Files.createTempDirectory("jib-repro");
dependencies = Arrays.stream(System.getProperty("app.classpath").split(":"))
.map(Path::of).toList();
Path source = work.resolve("src/demo/App.java");
Files.createDirectories(source.getParent());
Files.writeString(source, "package demo; public class App {"
+ " public static void main(String[] a) { System.out.println(\"hi\"); } }");
Path classes = Files.createDirectories(work.resolve("classes"));
javax.tools.ToolProvider.getSystemJavaCompiler().run(null, null, null,
"-d", classes.toString(), source.toString());
Path resources = Files.createDirectories(work.resolve("resources"));
Files.writeString(resources.resolve("application.properties"), "greeting=hi\n");
List<String> a = build("a", classes, resources, false);
// Build b: same content, but every file has a new modification time, as after
// a fresh checkout or a clean build on another CI runner
Thread.sleep(1100);
for (Path dir : List.of(classes, resources)) {
try (var files = Files.walk(dir)) {
for (Path f : files.toList()) {
Files.setLastModifiedTime(f, FileTime.from(Instant.now()));
}
}
}
List<String> b = build("b", classes, resources, false);
// Build c: one property changed
Files.writeString(resources.resolve("application.properties"), "greeting=hello\n");
List<String> c = build("c", classes, resources, false);
// Build d: content of a, but with real file times and the real build time,
// which is what an image build that keeps timestamps produces
Files.writeString(resources.resolve("application.properties"), "greeting=hi\n");
List<String> d = build("d", classes, resources, true);
String[] names = {"image ID", "dependencies", "resources", "classes"};
System.out.println(" a b c d");
for (int i = 0; i < names.length; i++) {
System.out.printf("%-13s %s %s %s %s%n", names[i], a.get(i), b.get(i),
c.get(i), d.get(i));
}
try (var paths = Files.walk(work)) {
paths.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
}
}
/** Builds an image tar; returns the start of the image ID and of each layer's diff ID. */
static List<String> build(String name, Path classes, Path resources, boolean realTimes)
throws Exception {
JavaContainerBuilder java = JavaContainerBuilder.from("scratch")
.addDependencies(dependencies)
.addResources(resources)
.addClasses(classes)
.setMainClass("demo.App");
if (realTimes) {
java.setModificationTimeProvider((file, target) -> lastModified(file));
}
JibContainerBuilder image = java.toContainerBuilder();
if (realTimes) {
image.setCreationTime(Instant.now());
}
Path tar = work.resolve(name + ".tar");
String id = image.containerize(Containerizer.to(TarImage.at(tar).named("demo:" + name))
.setBaseImageLayersCache(work.resolve("cache-base"))
.setApplicationLayersCache(work.resolve("cache-app-" + name)))
.getImageId().getHash();
List<String> result = new ArrayList<>();
result.add(id.substring(0, 12));
for (JsonElement diffId : readConfig(tar).getAsJsonObject("rootfs")
.getAsJsonArray("diff_ids")) {
result.add(diffId.getAsString().substring(7, 19));
}
return result;
}
static Instant lastModified(Path file) {
try {
return Files.getLastModifiedTime(file).toInstant();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
static JsonObject readConfig(Path tar) throws IOException {
try (TarArchiveInputStream in = new TarArchiveInputStream(Files.newInputStream(tar))) {
for (TarArchiveEntry e; (e = in.getNextEntry()) != null; ) {
if (e.getName().equals("config.json")) {
return JsonParser.parseString(new String(in.readAllBytes(),
StandardCharsets.UTF_8)).getAsJsonObject();
}
}
}
throw new IllegalStateException("no config.json in " + tar);
}
}
a b c d
image ID 023a1e5e48cb 023a1e5e48cb 8c5ce60f1179 075e9dc4eee7
dependencies 12a526f60724 12a526f60724 12a526f60724 01eacc8664be
resources 70384490e9df 70384490e9df 2ed94a99a811 5bb1527ae8af
classes 8e96b0bac8bb 8e96b0bac8bb 8e96b0bac8bb 027c535053f3
- Builds a and b produced the same image ID and the same three diff IDs, although every class and resource file had a different modification time. Jib ignored the times, so a rebuild on another CI runner with the same JDK and dependencies gives the same image.
- Build c changed only the resources diff ID. The dependencies layer, 41 JARs of 21.7 MB (19.7 MB gzipped), is identical, so a registry that already has it receives only the small resources layer, a new config and a new manifest.
- Build d has the content of a but a different digest for every layer and for the image. A tar layer stores each file's time, so the digest now depends on when the files were written. In column d, the image ID, resources and classes change on every run, because those files are written fresh each time. The dependencies stay the same only because the JARs in the local Maven repository keep their download time; a CI runner with an empty Maven cache downloads them again and gets a new digest. Columns a to c never change.
The other approaches can be reproducible too:
- Dockerfile with BuildKit: setting
, usually to the time of the last commit, fixes theSOURCE_DATE_EPOCH times in the config and history (BuildKit 0.11 and later). File times inside the layers also needcreated on the image output (BuildKit 0.13 and later), for examplerewrite-timestamp=true on--output type=image,name=...,push=true,rewrite-timestamp=true . Adocker buildx build or a Maven build inside the Dockerfile can still download different files from day to day.RUN apt-get - Buildpacks: images get a fixed creation date of 1 January 1980 by default, and the same source, builder and buildpacks give the same digest. Spring Boot's
option sets another fixed date, orcreatedDate for the build time;now gives up reproducibility.now
Jib in a Maven or Gradle build
In a real project, the plugin reads the runtime classpath, resources and classes, and picks the main class from the build configuration. A typical setup pins the base image by digest, since an unpinned tag can change under you and break reproducibility. The configuration below follows the jib-maven-plugin
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>3.5.2</version>
<configuration>
<from>
<!-- replace ... with the digest of the image you tested -->
<image>eclipse-temurin:21-jre@sha256:...</image>
</from>
<to>
<!-- the property is set by git-commit-id-maven-plugin -->
<image>registry.example.com/payments/payment-service:${git.commit.id.abbrev}</image>
</to>
<container>
<jvmFlags>
<jvmFlag>-XX:MaxRAMPercentage=75</jvmFlag>
</jvmFlags>
<user>10001:10001</user>
<ports>
<port>8080</port>
</ports>
</container>
</configuration>
</plugin>
# push straight to the registry: no Docker daemon needed
# (in CI, run mvn verify jib:build so that the tests pass before the push)
mvn compile jib:build
# load into the local Docker daemon instead (needs the docker CLI)
mvn compile jib:dockerBuild
# write target/jib-image.tar, like the first program on this page
mvn compile jib:buildTar
- No fat JAR: Jib's default
iscontainerizingMode : it copies the class files and dependency JARs as separate files, so it works fromexploded andtarget/classes is enough. Themvn compile mode copies the built JAR instead; the Jib FAQ advises against it, especially for fat JARs such as Spring Boot's.packaged - Tags: put the tag in
. Without one, Jib pushes<to><image> , and:latest only adds tags to it, so every build, branch builds included, would overwrite<tags> .latest - Registry credentials:
talks to the registry itself, using Docker credential helpers,jib:build , or credentials in the plugin configuration. In CI, this removes the need for~/.docker/config.json and a Docker-in-Docker setup.docker login - Gradle: the
plugin offers the same three tasks,com.google.cloud.tools.jib ,jib andjibDockerBuild .jibBuildTar - Multi-platform images: Jib can build an image for several platforms, such as
andlinux/amd64 , from a multi-platform base image, but only when pushing to a registry, not into a tar file or a daemon; the Jib FAQ still calls this feature incubating. Withoutlinux/arm64 , Jib picks<platforms> , even on an ARM machine such as an Apple Silicon Mac.linux/amd64
A multi-stage Dockerfile, for comparison
A Dockerfile gives control that Jib and Buildpacks do not: any operating system package, file layout or build step, such as installing certificates or native libraries. This is a compact version of the layered build from
# syntax=docker/dockerfile:1
# replace ... with the digests of the images you tested; the build stage runs
# on the build machine's platform, also in a multi-platform build
FROM --platform=$BUILDPLATFORM eclipse-temurin:21-jdk@sha256:... AS build
WORKDIR /src
COPY .mvn/ .mvn/
COPY mvnw pom.xml ./
RUN ./mvnw -q dependency:go-offline
COPY src/ src/
# pom.xml sets <finalName>app</finalName>, so the JAR name is fixed
RUN ./mvnw -q package -DskipTests \
&& java -Djarmode=tools -jar target/app.jar extract --layers --launcher --destination /layers
FROM eclipse-temurin:21-jre@sha256:...
# Ubuntu images since 23.04 have user ubuntu with UID 1000, so use 10001
RUN groupadd --system --gid 10001 app \
&& useradd --system --uid 10001 --gid 10001 --no-create-home app
WORKDIR /app
COPY --from=build /layers/dependencies/ ./
COPY --from=build /layers/spring-boot-loader/ ./
COPY --from=build /layers/snapshot-dependencies/ ./
COPY --from=build /layers/application/ ./
USER 10001:10001
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "org.springframework.boot.loader.launch.JarLauncher"]
Four details avoid common failures:
- UID 1000:
is based on Ubuntu, 26.04 at the time of writing; the tag moved there from 24.04, which theeclipse-temurin:21-jre tag still uses. Canonical's Ubuntu images include a user21-jre-noble with UID 1000 from 23.04 on, soubuntu fails there;useradd --uid 1000 checks your base.docker run --rm eclipse-temurin:21-jre getent passwd 1000 - Numeric user: a named
makes pods withUSER app and norunAsNonRoot: true fail to start, because the kubelet cannot verify that a name is not root.runAsUser - Fixed JAR name: the extract command can name
directly; a glob such astarget/app.jar could also match atarget/*.jar or-sources JAR.-javadoc - Build platform:
runs the Maven stage once, natively, instead of once per target platform under emulation; the JAR is the same for every platform.--platform=$BUILDPLATFORM
This reaches a layer split similar to Jib's, but you maintain the split, the user and the entrypoint yourself, and the layers carry real file times unless the build rewrites them. In return, the Dockerfile works for any language, and anyone who knows Docker can read it.
Buildpacks with spring-boot:build-image
Buildpacks go the other way: no image instructions at all. The Spring Boot plugin starts the builder image in Docker, and the Paketo Java buildpacks detect a Spring Boot JAR and contribute:
- a JRE;
- a memory calculator that sets the heap from the container's memory limit at startup;
- the application, split into slices from the JAR's layer index;
- a non-root user to run the application as.
Not run here, since it needs a Docker daemon:
# Maven: build an image in the local Docker daemon
./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=payments/payment-service:1.0
# Gradle
./gradlew bootBuildImage --imageName=payments/payment-service:1.0
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<image>
<name>registry.example.com/payments/${project.artifactId}:${project.version}</name>
<publish>false</publish>
</image>
</configuration>
</plugin>
- Builder: Spring Boot 4.1 defaults to
, a small Ubuntu Noble-based image, as apaketobuildpacks/builder-noble-java-tiny tag. Pin the builder and buildpack versions to get the same image from the same source next month.latest - Daemon: the goal needs access to a Docker daemon, found from the Docker CLI configuration or
; the Spring Boot documentation also shows Podman. In CI, that means a runner with Docker, which Jib does not need.DOCKER_HOST - Publishing: setting
topublish pushes the image to the registry in its name, using the credentials undertrue .docker.publishRegistry - Base image updates: buildpack images separate the run image (the operating system) from the application layers, so
can swap in a patched run image without rebuilding the application (pack rebase is the Buildpacks command-line tool).pack
The trade-off is control. You configure buildpacks through environment variables such as BP_JVM_VERSION
Comparing the results
| Concern | Dockerfile | Jib | Buildpacks |
|---|---|---|---|
| Reproducibility | Extra work: SOURCE_DATE_EPOCH | By default once the base image is pinned, shown above | Fixed dates by default; same digest when builder and buildpacks are pinned |
| Layering for Java | As good as you write it; layered JAR extraction by hand | Automatic: dependencies, resources and classes in separate layers | Automatic from Spring Boot's layer index |
| Base image | Any | Any image in a registry, a daemon or a tar; Temurin JRE by default | The builder's run image |
| Rebuild after a code change | Fast with good layer order and a layer cache (on CI, import it with --cache-from | Fast: only the classes layer is rebuilt and pushed | Slower: the builder runs again, though it reuses cached layers |
| OS packages, native libraries | Anything | Only through a custom base image | Only through buildpacks |
| Other languages | Yes | No: JVM applications only | Yes, with other buildpacks |
| SBOM and provenance | BuildKit attestations: provenance by default, SBOM with --sbom=true | None built in; use the CycloneDX Maven plugin or Syft | Paketo writes SBOMs (Syft, SPDX, CycloneDX) into the image; pack sbom download |
| Multi-platform images | docker buildx build --platform linux/amd64,linux/arm64FROM --platform=$BUILDPLATFORM | Yes, with <platforms><from> | One platform per build, chosen with imagePlatform |
| CI fit | Needs a builder service, a privileged runner, or rootless BuildKit or Buildah | Any runner with a JDK and registry credentials | Needs Docker on the runner |
Which to use
| Situation | Choose | Why |
|---|---|---|
| Java services built in CI without Docker access | Jib | Builds and pushes from the Maven or Gradle JVM; reproducible once the base image is pinned |
| Spring Boot team that wants good defaults with no image code | Buildpacks | JRE, memory settings, layers and non-root user chosen for you |
| Image needs OS packages, native libraries or an unusual layout | Dockerfile | Full control over every step |
| Mixed languages under one build standard | Dockerfile or Buildpacks | Both work for any language; Jib is Java only |
| Security team requires byte-identical rebuilds | Jib with a pinned base image, or Buildpacks with pinned builder and buildpacks | Same input, same digest, no extra build settings |
| Fastest rebuild after a code change | Jib | Rebuilds and pushes one small layer |
A pinned base image does not get security fixes on its own. Let Renovate or Dependabot propose digest updates, and rebuild on a schedule so that operating system fixes reach images whose code has not changed. Dependabot does not read image references in pom.xmlbuild.gradleexecpreStopsh -c "sleep 10"sleep
Whichever you pick: pin the base image or builder by digest and update it on purpose, tag images with the commit ID, run as a non-root user, and size the JVM to the container (see -Xmx-XX:MaxRAMPercentage