Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Lean Spring Boot Containers

Lean Spring Boot Containers

Sascha Selzer

October 28, 2026

Transcript

48 slides
  1. Agenda 01 Why small images? 02 Analysing images: SBOMs, CVEs,

    licences, layers 03 The example application 04 Prune dependencies: static vs. runtime analysis 05 Optimised JRE with jdeps + jlink 06 Shrink the OS layer: ready-made or build your own 07 The final image and takeaways OPENVALUE DÜSSELDORF GMBH 3 / 48 3
  2. Google: performance and security Performance Security Pushed and pulled on

    every deploy Smaller attack surface Pulled again on scale-out and rescheduling Fewer packages with vulnerabilities Sandeep Dinesh, “Kubernetes best practices: How and why to build small container images”, Google Cloud blog, 2018. OPENVALUE DÜSSELDORF GMBH 5 / 48 5
  3. Docker: build best practices Minimal base image Multi-stage builds No

    “nice to have” packages .dockerignore Rebuild often Pin base images Source: docs.docker.com/build/building/best-practices OPENVALUE DÜSSELDORF GMBH 6 / 48 6
  4. Size costs time at startup 76% of container start time

    is pulling the image 6.4% of pulled data is read at startup Harter et al., “Slacker”, USENIX FAST '16 OPENVALUE DÜSSELDORF GMBH 7 / 48 7
  5. Size costs security 87% 15% 500+ of images have high/critical

    vulnerabilities of those are in packages loaded at runtime vulnerabilities in the official node image Sysdig 2023 · Snyk 2019 · Alert Logic 2018 · Datadog Security Labs · Trend Micro 2022 OPENVALUE DÜSSELDORF GMBH 8 / 48 8
  6. Not small for its own sake If the app doesn't

    need it, it's only a cost. OPENVALUE DÜSSELDORF GMBH 9 / 48 9
  7. CVEs: visibility is only the first step Discover Inventory packages

    → Assess Severity, reachability, fixes → Reduce Remove what isn't needed A scanner finding is not a risk decision. OPENVALUE DÜSSELDORF GMBH 10 / 48 10
  8. Syft Generates an SBOM OS packages + Java JARs CycloneDX,

    SPDX, Syft JSON github.com/anchore/syft Syft · SBOM generator OPENVALUE DÜSSELDORF GMBH 12 / 48 12
  9. Grype Scans for known CVEs Images, filesystems, SBOMs Fails CI

    above a severity threshold github.com/anchore/grype Grype · Vulnerability scanner OPENVALUE DÜSSELDORF GMBH 13 / 48 13
  10. Grant Checks licences Lists licences of all packages Allow/deny rules

    github.com/anchore/grant Grant · Licence scanner OPENVALUE DÜSSELDORF GMBH 14 / 48 14
  11. Dive Explore an image layer by layer Files per layer

    Wasted space, efficiency score dive github.com/wagoodman/dive Dive · Layer explorer OPENVALUE DÜSSELDORF GMBH 15 / 48 15
  12. Finding CVEs is easy. Analysing them is hard. So ship

    fewer artefacts. OPENVALUE DÜSSELDORF GMBH 16 / 48 16
  13. Demo: a typical Spring Boot service Movie service: REST CRUD,

    persisted in PostgreSQL, events to Kafka. Starters spring-boot-starter-webmvc spring-boot-starter-jackson Spring Boot 4.1 · Java 25 spring-boot-starter-validation spring-boot-starter-data-jpa spring-boot-starter-liquibase spring-boot-starter-kafka postgresql OPENVALUE DÜSSELDORF GMBH 17 / 48 17
  14. The default Dockerfile # src/main/docker/Dockerfile FROM bellsoft/liberica-openjre-debian:25-cds AS builder WORKDIR

    /builder ARG JAR_FILE=target/*.jar COPY ${JAR_FILE} application.jar RUN java -Djarmode=tools -jar application.jar \ extract --layers --destination extracted Multi-stage build Layered jar Full JRE (with CDS) on Debian Spring Boot docs: Dockerfiles FROM bellsoft/liberica-openjre-debian:25-cds WORKDIR /application 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/ ./ ENTRYPOINT ["java", "-jar", "application.jar"] OPENVALUE DÜSSELDORF GMBH 18 / 48 18
  15. What's inside the 463 MB image? 83 MB 192 MB

    App + jar dependencies 188 MB Java runtime OS base 429 119 91 48 vulnerabilities Debian packages jars Java modules in the JDK OPENVALUE DÜSSELDORF GMBH 19 / 48 19
  16. Static analysis: dependency:analyze Compiled classes → ./mvnw dependency:analyze Used undeclared:

    declare explicitly Unused declared: candidates to remove OPENVALUE DÜSSELDORF GMBH Referenced classes in bytecode → Compare with the pom [WARNING] Used undeclared dependencies found: org.springframework:spring-context org.springframework:spring-web org.springframework.data:spring-data-jpa org.springframework.kafka:spring-kafka … [WARNING] Unused declared dependencies found: spring-boot-starter-webmvc spring-boot-starter-data-jpa spring-boot-starter-liquibase spring-boot-starter-kafka org.postgresql:postgresql … 21 / 48 21
  17. Limits of static analysis All 12 declared dependencies reported as

    unused, including the database driver. Blind to runtime wiring Only direct dependencies Auto-configuration Transitive jars are not checked Reflection and ServiceLoader The waste hides in what starters pull in JDBC driver lookup OPENVALUE DÜSSELDORF GMBH 22 / 48 22
  18. Runtime analysis: loosejar Run representative flows loosejar agent records loaded

    JARs Review before removing OPENVALUE DÜSSELDORF GMBH # Extract the Spring Boot archive java -Djarmode=tools -jar target/movie-service.jar \ extract --destination extracted # Run with the loosejar agent java -javaagent:./extracted/loosejar-1.2.0.jar \ -Dloosejar.outputFile=test.csv \ -Dloosejar.format=csv \ -jar extracted/application/movie-service.jar 23 / 48 23
  19. Static vs. runtime analysis Static: dependency:analyze Runtime: loosejar Looks at

    Bytecode references Classes actually loaded Reflection, ServiceLoader, auto-config invisible visible Transitive jars not checked checked Needs a build a running app + test flows Risk false "unused" untested paths look unused OPENVALUE DÜSSELDORF GMBH 24 / 48 24
  20. Remove only what evidence says is unused 13 libraries never

    loaded ≈ −14 MB image size OPENVALUE DÜSSELDORF GMBH <!-- pom.xml, profile "optimized" --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-liquibase</artifactId> <exclusions> <exclusion> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> </exclusion> <exclusion> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> </exclusion> <exclusion> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> </exclusion> </exclusions> </dependency> 25 / 48 25
  21. Going further: question the features JPA → JDBC Spring Data

    JPA replaced by Spring Data JDBC ≈ −24 MB additional image size OPENVALUE DÜSSELDORF GMBH Do we really need the feature, or is there a simpler alternative? No Hibernate, no bytecode enhancement, no proxies Usually not an option, or not an easy one: it means changing application code, not just the build. 26 / 48 26
  22. The modular JDK and the end of the JRE Java

    9 (JPMS): the JDK is split into modules, and jlink links only the ones you need OpenJDK considers the JRE legacy after Java 8 Aug 2021: Temurin drops JREs for Java 17 Dec 2021: JREs are back after user demand Recommended: build your own JRE from a JDK with only the modules the app uses OPENVALUE DÜSSELDORF GMBH java --list-modules (Zulu 25, 71 modules) Java SE (22): java.base java.compiler java.datatransfer java.desktop java.instrument java.logging java.management java.management.rmi java.naming java.net.http java.prefs java.rmi java.scripting java.se java.security.jgss java.security.sasl java.smartcardio java.sql java.sql.rowset java.transaction.xa java.xml java.xml.crypto JDK (47): jdk.accessibility jdk.attach jdk.charsets jdk.compiler jdk.crypto.cryptoki jdk.crypto.ec jdk.dynalink jdk.editpad jdk.graal.compiler jdk.graal.compiler.management jdk.hotspot.agent jdk.httpserver jdk.incubator.vector jdk.internal.ed jdk.internal.jvmstat jdk.internal.le jdk.internal.md jdk.internal.opt jdk.internal.vm.ci jdk.jartool jdk.javadoc jdk.jcmd jdk.jconsole jdk.jdeps jdk.jdi jdk.jdwp.agent jdk.jfr jdk.jlink jdk.jpackage jdk.jshell jdk.jsobject jdk.jstatd jdk.localedata jdk.management jdk.management.agent jdk.management.jfr jdk.naming.dns jdk.naming.rmi jdk.net jdk.nio.mapmode jdk.sctp jdk.security.auth jdk.security.jgss jdk.unsupported jdk.unsupported.desktop jdk.xml.dom jdk.zipfs + 2 Azul vendor modules (com.azul.*) 28 / 48 28
  23. Build a JRE for this application 1. Analyse jdeps jdeps

    --ignore-missing-deps -q \ --recursive \ --print-module-deps \ --multi-release 25 \ --class-path 'extracted/lib/*' \ extracted/application/movie-service.jar OPENVALUE DÜSSELDORF GMBH → 2. Select Required modules 3. Assemble jlink → 20 of 48 modules needed 29 / 48 29
  24. Use jlink to trim the JRE jlink \ --add-modules $(cat

    deps.info) \ --strip-debug \ --compress zip-9 \ --no-header-files \ --no-man-pages \ --output /myjre OPENVALUE DÜSSELDORF GMBH Standard ~192 MB Custom 66 MB ~126 MB saved 30 / 48 30
  25. What does java need from the OS? # Direct dependencies

    of the launcher $ ldd $JAVA_HOME/bin/java linux-vdso.so.1 libjli.so => $JAVA_HOME/lib/libjli.so libc.so.6 => /lib/aarch64-linux-gnu/libc.so.6 libdl.so.2 => /lib/aarch64-linux-gnu/libdl.so.2 libpthread.so.0 => /lib/aarch64-linux-gnu/libpthread.so.0 /lib/ld-linux-aarch64.so.1 # All native libs of the custom JRE $ for f in $JAVA_HOME/lib/*.so \ $JAVA_HOME/lib/server/*.so; do ldd "$f"; done | awk '{print $1}' | sort -u OPENVALUE DÜSSELDORF GMBH glibc is all the custom JRE links against libc, libm, libdl, libpthread, librt, ld-linux zlib, freetype etc. are bundled in the JDK X11 / ALSA only for AWT: not needed on a server 32 / 48 32
  26. The default base image is a full Debian # FROM

    bellsoft/liberica-openjre-debian:25-cds $ cat /etc/os-release PRETTY_NAME="Debian GNU/Linux 12 (bookworm)" VERSION="12 (bookworm)" VERSION_CODENAME=bookworm ID=debian # Count the Debian packages $ syft -q bellsoft/liberica-openjre-debian:25-cds \ | grep -c ' deb' 119 119 deb packages, only libc6 needed by the JRE Shells: bash, dash Package managers: apt, dpkg Downloader: curl Archivers: tar, gzip Interpreter: perl-base User admin: passwd, login (su) System tools: mount, util-linux, e2fsprogs OPENVALUE DÜSSELDORF GMBH 33 / 48 33
  27. What are distroless images? App + runtime dependencies. Nothing else.

    Classic base Distroless Shell bash / sh none Package manager apt / dnf / apk none Packages ~100+ a handful Scanner findings many few Debugging docker exec kubectl debug, :debug tags OPENVALUE DÜSSELDORF GMBH 34 / 48 34
  28. Two ways to a minimal OS layer A · Use

    a ready-made image B · Build your own Docker Hardened Images Chisel: cut package slices Red Hat Project Hummingbird apko: declare the image Chainguard Images debootstrap: extract debs into an empty root Google distroless, UBI micro, Chiselled Ubuntu, … dnf --installroot: install into an empty root OPENVALUE DÜSSELDORF GMBH 35 / 48 35
  29. A · Ready-made distroless images Image Example Built from Docker

    Hardened Images dhi.io/… Debian / Alpine Project Hummingbird quay.io/hummingbird/… Fedora Chainguard Images cgr.dev/chainguard/glibc-dynamic Wolfi Google distroless gcr.io/distroless/cc-debian12 Debian Red Hat UBI 10 micro redhat/ubi10-micro RHEL 10 Chiselled Ubuntu ubuntu/jre:21-24.04_stable Ubuntu Paketo tiny paketobuildpacks/builder-noble-java-tiny Ubuntu 24.04 OPENVALUE DÜSSELDORF GMBH 36 / 48 36
  30. B · Chisel Cuts slices out of Ubuntu packages File-level,

    not package-level No shell needed Regular Ubuntu security updates github.com/canonical/chisel OPENVALUE DÜSSELDORF GMBH # Dockerfile.chisel (abridged) FROM ubuntu:24.04 AS os ADD .../chisel_v1.1.0_linux_amd64.tar.gz chisel.tar.gz RUN tar -xf chisel.tar.gz -C /usr/bin \ && chisel cut --release ubuntu-24.04 \ --root /staging-rootfs \ base-files_base base-files_release-info \ base-files_chisel libc6_libs tzdata_zoneinfo FROM scratch COPY --from=os /staging-rootfs / COPY --from=builder /myjre /usr/java/jdk25 37 / 48 37
  31. What is a slice? A slice is a named subset

    of a package's files Slices declare dependencies on other slices, not whole packages Debian package A A_slice2 A_slice1 A_slice3 Package B needs all of A, its slices only need A_slice1 and A_slice2 A_slice3 never ends up in the image # slice name = <package>_<slice> libc6_libs tzdata_zoneinfo base-files_release-info B_slice1 B_slice2 Diagram: canonical/chisel README Debian package B OPENVALUE DÜSSELDORF GMBH 38 / 48 38
  32. B · apko Declarative images from APK packages No Dockerfile

    Reproducible, multi-arch SBOM included github.com/chainguard-dev/apko # apko.yaml contents: repositories: [https://packages.wolfi.dev/os] keyring: - https://packages.wolfi.dev/os/wolfi-signing.rsa.pub packages: - wolfi-baselayout - glibc - ca-certificates-bundle - tzdata accounts: groups: [{groupname: nonroot, gid: 65532}] users: [{username: nonroot, uid: 65532, gid: 65532}] run-as: 65532 archs: [x86_64, aarch64] # build an image tarball apko build apko.yaml movie-base:latest base.tar OPENVALUE DÜSSELDORF GMBH 39 / 48 39
  33. B · debootstrap Extracts Debian packages into an empty root

    Own suite script: only base-files + libc6 Extract only, no maintainer scripts, no shell dpkg status written, stays scannable salsa.debian.org/installer-team/debootstrap # Dockerfile.debian (abridged) FROM debian:trixie AS os RUN apt-get install -y debootstrap COPY <<"EOF" /usr/share/debootstrap/scripts/distroless . "$DEBOOTSTRAP_DIR/scripts/debian-common" work_out_debs () { required="base-files libc6" EXCLUDE_DEPENDENCY="$EXCLUDE_DEPENDENCY debconf mawk awk" } first_stage_install () { extract $required # + write var/lib/dpkg/status for Syft/Grype } EOF RUN debootstrap --foreign --variant=- \ trixie /staging-rootfs \ http://deb.debian.org/debian distroless FROM scratch COPY --from=os /staging-rootfs / OPENVALUE DÜSSELDORF GMBH 40 / 48 40
  34. B · dnf --installroot Install RPMs into an empty root

    Fedora, RHEL/UBI, Alma, Rocky, … Whole packages, coarser than Chisel RPM DB stays scannable # Dockerfile.fedora (abridged) FROM fedora:latest AS os RUN dnf install -y \ --installroot=/staging-rootfs \ --use-host-config \ --releasever="$(rpm -E %fedora)" \ --setopt=install_weak_deps=False \ --nodocs \ glibc \ && dnf clean all --installroot=/staging-rootfs # drop what glibc pulled in, keep the rest RUN rpm --root=/staging-rootfs -e --nodeps \ bash ncurses-base ncurses-libs \ fedora-release fedora-release-common \ fedora-release-identity-basic \ fedora-repos fedora-gpg-keys gpg-pubkey FROM scratch COPY --from=os /staging-rootfs / COPY --from=builder /myjre /opt/java OPENVALUE DÜSSELDORF GMBH 41 / 48 41
  35. Keep the runtime essentials $ syft -q movie-service:fedora | grep

    -c ' rpm ' 6 RPM packages Purpose glibc, glibc-common, glibc-minimallangpack C runtime libgcc GCC runtime library filesystem, setup Directory tree, /etc/passwd OPENVALUE DÜSSELDORF GMBH Debian 188 MB Minimal 13 MB ~175 MB saved 6 rpm packages instead of 119 deb 42 / 48 42
  36. Ready-made or build your own? A · Ready-made B ·

    Build your own + Vendor support and patch SLAs + Exactly what the app needs, nothing more + Near-zero CVE targets, VEX statements + Full control over content and update timing + Full SBOM, signatures, SLSA provenance out of the box + Free, any distribution + No base-image pipeline to run − You own rebuilds, patching and CVE triage − May not fit 100%: extra or missing packages − SBOM, signing and provenance are your job − Licensing, subscription and vendor lock-in − No vendor support, needs expertise OPENVALUE DÜSSELDORF GMBH 43 / 48 43
  37. What's inside the 148 MB image? 69 MB 66 MB

    App + jar dependencies Custom JRE 13 MB OS base 18 6 78 20 vulnerabilities (−96%) RPM packages (−95%) jars (−14%) Java modules in the JRE (−58%) OPENVALUE DÜSSELDORF GMBH 45 / 48 45
  38. Smallest isn't always best Specialised production Shared platform Minimal, purpose-built

    images Reusable base images Smaller footprint Better layer caching Smaller attack surface Reuse across services OPENVALUE DÜSSELDORF GMBH 46 / 48 46
  39. Further reading Why small images Analyse images Trim dependencies Google:

    why build small images Syft: SBOM Maven: dependency:analyze Docker: build best practices Grype: vulnerabilities DepClean Slacker (USENIX FAST '16) Grant: licences loosejar GKE image streaming Dive: layers Spring Boot: Dockerfiles Custom JRE Ready-made images Build your own OS layer JDK 25: jdeps Docker Hardened Images Chisel · chisel-releases JDK 25: jlink Project Hummingbird · Chainguard apko · Wolfi JEP 282: jlink Google distroless · UBI micro debootstrap Adoptium: Temurin JREs are back Chiselled Ubuntu · Paketo Demo repository + Dockerfiles OPENVALUE DÜSSELDORF GMBH 47 / 48 47
  40. That's all. Thank you! OPENVALUE DÜSSELDORF GMBH Get the slides

    Let's connect on LinkedIn speakerdeck.com/tommy1199/lean-spring-boot-containers linkedin.com/in/sse82 48 / 48 48

Other Decks in Programming