How to create custom jre using jdeps and jlink?

114 Views Asked by At

I'm trying to build a custom jre for my spring boot application. I created a docker file to first run jdeps and then putting together the jre

This is my docker file.

ARG ALPINE_VERSION=3.18.5
ARG JAVA_VERSION=21.0.1
FROM azul/zulu-openjdk-alpine:${JAVA_VERSION} AS builder
WORKDIR /build
USER root
COPY build/libs/pet-service.jar application.jar
RUN apk add --no-cache binutils --repository=https://dl-cdn.alpinelinux.org/alpine/edge/main/ \
    && jdeps --ignore-missing-deps -q --recursive --multi-release 21 --print-module-deps application.jar > deps.info \
    && cat deps.info \
    && jlink  --add-modules ${cat deps.info} --strip-debug --no-header-files --no-man-pages --output /myjre \
    && java -Djarmode=layertools -jar application.jar extract \
    && chown -R 1001:1001 .

FROM alpine:${ALPINE_VERSION}
ENV JAVA_HOME /user/java/jdk21
ENV PATH $JAVA_HOME/bin:$PATH
COPY --from=builder /myjre $JAVA_HOME
WORKDIR /application
COPY --from=builder /build/agent/ ./
COPY --from=builder /build/dependencies/ ./
COPY --from=builder /build/snapshot-dependencies/ ./
COPY --from=builder /build/spring-boot-loader/ ./
COPY --from=builder /build/application/ ./
USER 1001
ENV JAVA_OPTS ''
ENV MAIN_OPTS ''
ENTRYPOINT ["sh", "-c", "java ${JAVA_OPTS} org.springframework.boot.loader.launch.JarLauncher ${MAIN_OPTS}"]
EXPOSE 8080

Jdeps just finds java.base. So when I run the docker image I get a class not found for PropertyEditorSupporter. When I manually add the modules java.base and java.desktop without using the jdeps results, running the image stops after a short time, without logging anything, no error output.

I'm a little bit lost what to try next. I used an internal registry, so the adapted links to the docker images are maybe not functional, but it works for me locally

1

There are 1 best solutions below

0
Varun Nair On

Most likely it is because of the way Springboot packs all the dependencies in the fat jar. So one of the solutions is to first unpack the jar into your build or source directory.

jar xf target/JavaCoffeeShop.jar

Another way is to the maven-dependency-plugin and copy the dependencies into the build directory

See this article by Snyk for more details: https://medium.com/@snyksec/using-jlink-to-create-smaller-docker-images-for-your-spring-boot-java-application-5e21a3377965.