Build tools & artifact repositories · Lesson 7 of 9 · 3 min read
Builds inside containers and CI
Multi-stage Dockerfile for a Java service
# syntax=docker/dockerfile:1.7
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY gradlew settings.gradle.kts build.gradle.kts gradle.properties ./
COPY gradle ./gradle
RUN --mount=type=cache,target=/root/.gradle ./gradlew dependencies --no-daemon > /dev/null
COPY src ./src
RUN --mount=type=cache,target=/root/.gradle ./gradlew bootJar --no-daemon
FROM eclipse-temurin:21-jre
RUN useradd -r -u 10001 app
WORKDIR /app
COPY --from=build /src/build/libs/*.jar app.jar
USER 10001
ENTRYPOINT ["java","-XX:MaxRAMPercentage=75","-jar","/app/app.jar"]
- Copy build files first so the dependency layer is cached until they change.
- BuildKit cache mounts keep
~/.gradle/~/.m2between builds without bloating the image. - Runtime image is a JRE (or distroless) with a non-root user;
MaxRAMPercentagemakes the JVM respect container memory limits. - Spring Boot's layered jars (
java -Djarmode=layertools) or Jib split dependencies from application classes into separate layers, so only the small app layer changes per build. Jib builds images without Docker at all.
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.
Choices in CI
- Build the jar in CI and copy it into a slim image or build inside a multi-stage Dockerfile — either works; just build once and promote the image digest.
- Cache
~/.m2/~/.gradle(setup-javacache:, actions/cache, Jenkins persistent volumes) and use a remote Gradle build cache for large codebases. - Publish test reports (JUnit XML) and coverage (JaCoCo) as artifacts; enforce quality gates (SonarQube) without making the pipeline painfully slow.