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.

Share

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 load, manifest.json lists them by file name instead). A digest is a hash of the content, so it names exactly one version of a file. The three approaches for Java differ in who decides what goes into each layer, and in what the build machine needs:

  • 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 COPY or RUN that changes files becomes a layer.
  • 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 spring-boot:build-image and its Gradle task bootBuildImage use the Java buildpacks of Paketo, an open-source buildpacks project.
The three approaches at a glance
DockerfileJibBuildpacks (Spring Boot)
Configured inDockerfilepom.xml or build.gradlepom.xml or build.gradle, plus buildpack environment variables
Needs a Docker daemonYes, unless you use a daemonless builder such as Buildah or PodmanNo, except to load into a local daemonYes, or a compatible engine such as Podman
Default base imageWhatever FROM saysThe eclipse-temurin JRE tag for your Java version, a tag that moves; set <from> and pin itChosen by the builder (Ubuntu Noble-based for the default builder-noble-java-tiny)
LayersOne per instruction that changes filesDependencies, snapshot dependencies, project dependencies, resources, classesJRE, helpers such as the memory calculator, and the slices listed in Spring Boot's layer index, BOOT-INF/layers.idx

Docker for Java applications covers the Dockerfile techniques themselves (multi-stage builds, layered JARs, jlink runtimes and distroless images). This page compares the approaches and runs the one that works without Docker: Jib.

Building an image with Jib, no Docker required

The Jib plugins are thin wrappers around jib-core, a library with a builder API. Calling it from a program shows the core of what the plugins do. This program compiles a one-class Spring Boot application, then builds an image from it and the 41 JARs on the runtime classpath of spring-boot-starter-webmvc, the same inputs mvn jib:buildTar would use. It runs with jib-core 0.28.2 on the classpath.

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-jre. Instead, the program first builds its own base image: a Java runtime made with jlink, in one layer on an empty (scratch) image, saved as a tar file. Jib then reads that tar as the base, as it would read one from a registry. A runtime on an empty image has no C library, so neither image built here can start; they are for inspection only. A real base image provides the operating system files the JVM needs. The build itself is the JavaContainerBuilder chain in the middle; the rest prints what is in the tar.

Java
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...");
    }
}
Output
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 docker build, no container started. That is why Jib fits CI runners where Docker is not available or not allowed.
  • The tar holds four gzipped layers, named by the SHA-256 digest of their compressed bytes, plus config.json and manifest.json. docker load accepts this layout (not run here).
  • manifest.json names the image payment-service:1.0 and points to the config and the layers in order. The image ID printed first is the digest of 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 java -XX:MaxRAMPercentage=75 -cp /app/libs/*:/app/resources:/app/classes demo.App. 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. The java command is found through the PATH inherited from the base image.
  • Layer order: the base image's jre 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.
  • Timestamps: the image's created date is 1970-01-01, the Unix epoch, and every file is dated one second after it (EPOCH_PLUS_SECOND in the plugins' settings). Jib drops the real times on purpose, and that is what makes the build reproducible.
  • Ownership and modes: files belong to root (0:0) with mode 644. The java launcher gets mode 755 because the program passed a permissions function for the jre 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.
  • User: setUser("10001:10001") became the config's User field, so the container does not run as root. A numeric user also passes Kubernetes' runAsNonRoot check, which cannot verify a user name.
  • History: each layer has a comment naming it (jre, dependencies, resources, classes), which docker history shows in its COMMENT column. CREATED BY shows the Jib version where a Dockerfile build shows its instructions.

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 and /app/jib-main-class-file for custom entrypoints. The jib-core API used here writes neither unless you add them.

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:

Java
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);
    }
}
Output
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 SOURCE_DATE_EPOCH, usually to the time of the last commit, fixes the created times in the config and history (BuildKit 0.11 and later). File times inside the layers also need rewrite-timestamp=true on the image output (BuildKit 0.13 and later), for example --output type=image,name=...,push=true,rewrite-timestamp=true on docker buildx build. A RUN apt-get or a Maven build inside the Dockerfile can still download different files from day to day.
  • 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 createdDate option sets another fixed date, or now for the build time; now gives up reproducibility.

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 3.5.2 documentation; it was not run here, because Maven Central and the registries were not reachable:

XML
<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>
Shell
# 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 containerizingMode is exploded: it copies the class files and dependency JARs as separate files, so it works from target/classes and mvn compile is enough. The packaged mode copies the built JAR instead; the Jib FAQ advises against it, especially for fat JARs such as Spring Boot's.
  • Tags: put the tag in <to><image>. Without one, Jib pushes :latest, and <tags> only adds tags to it, so every build, branch builds included, would overwrite latest.
  • Registry credentials: jib:build talks to the registry itself, using Docker credential helpers, ~/.docker/config.json, or credentials in the plugin configuration. In CI, this removes the need for docker login and a Docker-in-Docker setup.
  • Gradle: the com.google.cloud.tools.jib plugin offers the same three tasks, jib, jibDockerBuild and jibBuildTar.
  • Multi-platform images: Jib can build an image for several platforms, such as linux/amd64 and linux/arm64, 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. Without <platforms>, Jib picks linux/amd64, even on an ARM machine such as an Apple Silicon Mac.

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 Docker for Java applications, where each part is explained. It was not run here, since no Docker daemon was available:

Dockerfile
# 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: eclipse-temurin:21-jre is based on Ubuntu, 26.04 at the time of writing; the tag moved there from 24.04, which the 21-jre-noble tag still uses. Canonical's Ubuntu images include a user ubuntu with UID 1000 from 23.04 on, so useradd --uid 1000 fails there; docker run --rm eclipse-temurin:21-jre getent passwd 1000 checks your base.
  • Numeric user: a named USER app makes pods with runAsNonRoot: true and no runAsUser fail to start, because the kubelet cannot verify that a name is not root.
  • Fixed JAR name: the extract command can name target/app.jar directly; a glob such as target/*.jar could also match a -sources or -javadoc JAR.
  • Build platform: --platform=$BUILDPLATFORM runs the Maven stage once, natively, instead of once per target platform under emulation; the JAR is the same for every platform.

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:

Shell
# 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
XML
<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 paketobuildpacks/builder-noble-java-tiny, a small Ubuntu Noble-based image, as a latest tag. Pin the builder and buildpack versions to get the same image from the same source next month.
  • Daemon: the goal needs access to a Docker daemon, found from the Docker CLI configuration or DOCKER_HOST; the Spring Boot documentation also shows Podman. In CI, that means a runner with Docker, which Jib does not need.
  • Publishing: setting publish to true pushes the image to the registry in its name, using the credentials under docker.publishRegistry.
  • Base image updates: buildpack images separate the run image (the operating system) from the application layers, so pack rebase can swap in a patched run image without rebuilding the application (pack is the Buildpacks command-line tool).

The trade-off is control. You configure buildpacks through environment variables such as BP_JVM_VERSION. Leave the Java version out: the plugin passes the one your compiler settings target, and a hard-coded value is easily forgotten at the next upgrade. Anything the buildpacks do not offer, such as an extra system package, needs a custom buildpack or a different approach.

Comparing the results

Dockerfile, Jib and Buildpacks compared
ConcernDockerfileJibBuildpacks
ReproducibilityExtra work: SOURCE_DATE_EPOCH, timestamp rewriting, pinned packagesBy default once the base image is pinned, shown aboveFixed dates by default; same digest when builder and buildpacks are pinned
Layering for JavaAs good as you write it; layered JAR extraction by handAutomatic: dependencies, resources and classes in separate layersAutomatic from Spring Boot's layer index
Base imageAnyAny image in a registry, a daemon or a tar; Temurin JRE by defaultThe builder's run image
Rebuild after a code changeFast with good layer order and a layer cache (on CI, import it with --cache-from)Fast: only the classes layer is rebuilt and pushedSlower: the builder runs again, though it reuses cached layers
OS packages, native librariesAnythingOnly through a custom base imageOnly through buildpacks
Other languagesYesNo: JVM applications onlyYes, with other buildpacks
SBOM and provenanceBuildKit attestations: provenance by default, SBOM with --sbom=trueNone built in; use the CycloneDX Maven plugin or SyftPaketo writes SBOMs (Syft, SPDX, CycloneDX) into the image; pack sbom download reads them
Multi-platform imagesdocker buildx build --platform linux/amd64,linux/arm64, with FROM --platform=$BUILDPLATFORM on the build stageYes, with <platforms> under <from>; registry push onlyOne platform per build, chosen with imagePlatform (Spring Boot 3.4 and later)
CI fitNeeds a builder service, a privileged runner, or rootless BuildKit or BuildahAny runner with a JDK and registry credentialsNeeds Docker on the runner

Which to use

Choosing a build approach
SituationChooseWhy
Java services built in CI without Docker accessJibBuilds 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 codeBuildpacksJRE, memory settings, layers and non-root user chosen for you
Image needs OS packages, native libraries or an unusual layoutDockerfileFull control over every step
Mixed languages under one build standardDockerfile or BuildpacksBoth work for any language; Jib is Java only
Security team requires byte-identical rebuildsJib with a pinned base image, or Buildpacks with pinned builder and buildpacksSame input, same digest, no extra build settings
Fastest rebuild after a code changeJibRebuilds 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.xml or build.gradle; for a Jib base image, use a Renovate custom regex manager. A distroless base image (see Docker for Java applications) and the tiny run image of the default Spring Boot builder have no shell, so a Kubernetes exec preStop hook such as sh -c "sleep 10" fails there; use the hook's built-in sleep action.

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 Docker for Java applications; with Buildpacks, the memory calculator sets -Xmx, which overrides any -XX:MaxRAMPercentage). To run the images, see Deploying Spring Boot on Kubernetes and Helm charts for Spring Boot.