How to run Java 20 in Docker

| 2 minutes read

Long story short, if you want (date of 11.08.2023) to run a Java 20 project (for example Spring Boot from Spring initializr) in a docker container, it is quite complicated.

There is no official gradle support for Java 20 yet since Java 17 is currently the LTS version.

That’s why I created a Dockerfile to run it anyways. Here is how and what we need. Documented in the Dockerfile.


FROM alpine AS base

# Add the testing and community cdn's of alpine linux to the containers image: https://wiki.alpinelinux.org/wiki/Repositories
RUN echo "https://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories
RUN echo "https://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories
# Update the dependencies
RUN apk update
# Add java 20 -> see the version here: https://pkgs.alpinelinux.org/package/edge/testing/aarch64/openjdk20
RUN apk add openjdk20=20.0.1_p9-r0

# Add gradle-> see the version here: https://pkgs.alpinelinux.org/package/edge/community/aarch64/gradle
RUN apk add gradle=8.2.1-r1

# Run a clean gradle build to check
RUN gradle clean build --no-daemon > /dev/null 2>&1 || true

# Create a build image from the base image to run the build
# This can be skipped and done in the base, but to not rebuild the base image every time, I cached this
FROM base AS build

# Copy the project into the image
# Copy will force the image to rebuild from this point every time on build -> cache is disabled from here afterwards
WORKDIR  /app
COPY . /app/

# Build the app
RUN gradle clean build --no-daemon

FROM base

EXPOSE 8080


# Set the environment variables
ENV SOME_ENV_VAR=test

COPY --from=build <YOUR_BUILD_JAR_PATH> /app/spring-boot-application.jar

ENTRYPOINT ["java", "-jar","/app/spring-boot-application.jar"]

Conclusion

This is it. So if you want to use Java 20 and don’t use the LTS version, this can be used. I hope it helped.

But all in all, I would recommend using the LTS (Java 17) for live projects 😁. But for testing, I would use it (or better go for Kotlin instead 🚀).


If you want to support this blog, you can buy me a coffee ☕️ or sign-up for my newsletter ✉️

comments powered by Disqus