if[-n"$CI"];thenecho"[CI] execution de javahello:mavenimage non executee : image non construite sur cet hote"elsedocker container run --label teaching-demo=true --rm javahello:mavenimagefi
[CI] execution de javahello:mavenimage non executee : image non construite sur cet hote
[CI] audit de l'image javahello:mavenimage non execute : hote Docker partage, aucun reseau garanti
ImportantAnalyse critique
Sécurité : L’image contient le code source, Maven et le JDK complet. C’est une surface d’attaque inutile.
Poids : L’image dépasse souvent les 800MB pour une application simple.
Image Java optimisée (multi-stage build)
Le Multi-stage build est la stratégie de référence. On utilise une image “lourde” pour compiler, puis on ne transfère que le .jar et les dépendances (lib/*.jar) vers une image JRE légère pour l’exécution.
Dockerfile.20.stage
# ============================================================# Stage 1: Build environment# ============================================================# Uses the full Maven SDK to compile the source code into a thin JARFROM maven:3.9.16-eclipse-temurin-25-noble AS stage-buildWORKDIR /app# Cache dependency layer: Copying only the wrapper and POM# allows Docker to skip downloading dependencies if they haven't changed.COPY .mvn/ .mvnCOPY mvnw pom.xml ./RUN./mvnw dependency:go-offline# Copy source code and perform a clean buildCOPY src ./src# Build using the 'jvm' profile (configured to output a thin JAR)RUN./mvnw clean package -DskipTests-Pjvm# ============================================================# Stage 2: Runtime environment# ============================================================# Uses the JRE-only base image to minimize the security attack surfaceFROM eclipse-temurin:25-jre-nobleLABEL maintainer="Emmanuel Bruno <emmanuel.bruno@univ-tln.fr>"LABEL description="Java Hello World Application - multi-stage"# Security: Create an unprivileged user/group to run the applicationRUNgroupadd-r appgroup &&useradd-r-g appgroup appuser &&\mkdir-p /app &&chown-R appuser:appgroup /app# Copy artifacts from the builder stage:# Only the thin JAR and external dependencies are required at runtime.COPY--from=stage-build--chown=appuser:appgroup /app/target/libs /app/libsCOPY--from=stage-build--chown=appuser:appgroup /app/target/hello-world-*.jar /app/app.jarUSER appuser# Configure JVM ergonomics for containerized environments:# JAVA_TOOL_OPTIONS is natively parsed by the JVM at startup,# ensuring memory limits are respected without needing shell script injection.ENV JAVA_TOOL_OPTIONS="-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0"# Execute the applicationENTRYPOINT ["java", "-jar", "/app/app.jar"]
[CI] audit de l'image javahello:mavenimagestage non execute : hote Docker partage, aucun reseau garanti
Prêt pour l’orchestration (Production-Ready)
Pour être orchestrée (Kubernetes, Compose), une image doit respecter des règles d’hygiène :
Non-Root : Vos Dockerfiles utilisent un appuser. Cela empêche une faille applicative de compromettre l’hôte.
Signaux (Exec Form) : L’usage de ENTRYPOINT ["/script.sh"] permet à la JVM de recevoir le SIGTERM pour un arrêt propre.
Mémoire : L’usage de -XX:MaxRAMPercentage permet à la JVM d’être “Container Aware”.
Affichage des images créées
docker image ls \--filter"reference=javahello"\--format"table {{.Repository}}\t{{.Tag}}\t{{.ID}}\t{{.Size}}\t{{.CreatedSince}}"
REPOSITORY TAG IMAGE ID SIZE CREATED
Accélérer les builds (Cache BuildKit)
Docker permet de monter des caches persistants pour le répertoire ~/.m2. Cela évite de retélécharger les dépendances à chaque modification du code source.
Dockerfile.30.cache
# ============================================================# Stage 1: Build Environment# Purpose: Leverage BuildKit caching to accelerate Maven builds# ============================================================FROM maven:3.9.16-eclipse-temurin-25-noble AS stage-buildWORKDIR /app# ------------------------------------------------------------# Layer 1: Maven Wrapper and Project Metadata# ------------------------------------------------------------# Copying the wrapper and POM first allows Docker to cache the# dependency resolution layer, skipping downloads if the project# structure hasn't changed.COPY .mvn/ .mvn/COPY mvnw pom.xml ./RUNchmod +x mvnw# ------------------------------------------------------------# Layer 2: Dependency Caching (BuildKit)# ------------------------------------------------------------# Using BuildKit's cache mount persists the local M2 repository# across builds, significantly reducing network overhead.RUN--mount=type=cache,target=/root/.m2\./mvnw--batch-mode dependency:go-offline# ------------------------------------------------------------# Layer 3: Application Build# ------------------------------------------------------------COPY src ./src# Compile the project using the 'jvm' profile.# The persistent cache ensures that even if sources change,# dependencies do not need to be re-downloaded.RUN--mount=type=cache,target=/root/.m2\./mvnw--batch-mode clean package -DskipTests-Pjvm# ============================================================# Stage 2: Runtime Environment# ============================================================# Using a JRE-only base image minimizes the attack surface# and keeps the final image size optimized for production.FROM eclipse-temurin:25-jre-nobleLABEL maintainer="Emmanuel Bruno <emmanuel.bruno@univ-tln.fr>"LABEL description="Java Hello World Application - BuildKit cache optimized"# Security: Create an unprivileged user/group to adhere to the principle of least privilegeRUNgroupadd-r appgroup &&useradd-r-g appgroup appuser &&\mkdir-p /app &&chown-R appuser:appgroup /app# ------------------------------------------------------------# Deployment: Copy artifacts from builder stage# ------------------------------------------------------------# We only copy the thin JAR and external dependencies required at runtime.COPY--from=stage-build--chown=appuser:appgroup /app/target/libs /app/libsCOPY--from=stage-build--chown=appuser:appgroup /app/target/hello-world-*.jar /app/app.jarUSER appuser# ------------------------------------------------------------# Runtime Execution# ------------------------------------------------------------# Configure JVM container ergonomics. JAVA_TOOL_OPTIONS is parsed# natively by the JVM, avoiding the need for shell script wrappers.ENV JAVA_TOOL_OPTIONS="-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0"# Execute the application. The JAR manifest is configured to# resolve external dependencies from the /app/libs/ directory.ENTRYPOINT ["java", "-jar", "/app/app.jar"]
[CI] audit de l'image javahello:dockercache non execute : hote Docker partage, aucun reseau garanti
Note
L’instruction --mount=type=cache,target=/root/.m2 est une fonctionnalité BuildKit qui transforme radicalement l’expérience de CI/CD.
Construction personnalisée (JDK + tarball Maven) — Avancé
Une construction multi-étages manuelle permet un contrôle granulaire sur les versions exactes de l’outillage : le JDK est verrouillé par l’image de base eclipse-temurin:25-jdk-noble, et Maven 3.9.16 est installé depuis un tarball Apache épinglé, indépendamment des images Maven officielles.
Dockerfile.40.manual
# ============================================================# Stage 1: Build Environment (Manual Toolchain)# Purpose: Demonstrate manual, reproducible toolchain provisioning:# the JDK is pinned by the base image tag and Maven by a# pinned Apache release tarball — combined with fixed# UID/GID file ownership for high-security CI.# ============================================================FROM eclipse-temurin:25-jdk-noble AS stage-build# Toolchain versioning for reproducible builds# (the JDK itself is pinned by the eclipse-temurin base image tag)ARG MAVEN_VERSION="3.9.16"ARG BUILDER_UID=2000ARG BUILDER_GID=2000LABEL maintainer="Emmanuel Bruno <emmanuel.bruno@univ-tln.fr>"LABEL description="Java Hello World Application - manual toolchain build"# ------------------------------------------------------------# OS Layer: Provision tools to fetch and verify the pinned# Apache Maven release (and to run the Maven wrapper).# ------------------------------------------------------------RUNapt-get update &&\apt-get install --yes--quiet--no-install-recommends\ ca-certificates curl unzip zip bash &&\rm-rf /var/lib/apt/lists/*# ------------------------------------------------------------# Security: Create dedicated builder user with deterministic UID/GID# ------------------------------------------------------------RUNgroupadd-g${BUILDER_GID} builder \&&useradd-m-u${BUILDER_UID}-g builder -s /bin/bash builder# ------------------------------------------------------------# Toolchain: Install a pinned Apache Maven release from the# official archive into a fixed prefix. Bounded 3-attempt# retry; fails loud if the tarball is missing or broken.# Runs as root so /opt/maven stays readable by the# unprivileged builder user.# ------------------------------------------------------------RUNMAVEN_HOME=/opt/maven;\MAVEN_TGZ="https://archive.apache.org/dist/maven/maven-3/${MAVEN_VERSION}/binaries/apache-maven-${MAVEN_VERSION}-bin.tar.gz";\for attempt in 1 2 3;do\echo">> Apache Maven ${MAVEN_VERSION}: attempt ${attempt}/3"&&\ifcurl-fsSL--connect-timeout 15 --max-time 300 -o /tmp/apache-maven.tar.gz "$MAVEN_TGZ"&&\tar-xzf /tmp/apache-maven.tar.gz -C /opt &&\mv /opt/apache-maven-${MAVEN_VERSION}"$MAVEN_HOME"&&\"$MAVEN_HOME/bin/mvn"-version;then\break;\fi;\echo">> attempt ${attempt} failed; removing partial Maven install before retry"&&\rm-rf /tmp/apache-maven.tar.gz "$MAVEN_HOME";\done&&\[-x"$MAVEN_HOME/bin/mvn"]||{echo"ERROR: Apache Maven ${MAVEN_VERSION} install failed after 3 attempts">&2;exit 1;}USER builderENV HOME=/home/builderENV PATH="/opt/maven/bin:${PATH}"SHELL ["/bin/bash", "-c"]WORKDIR /app# ------------------------------------------------------------# Layer: Dependency Resolution (BuildKit Cached)# ------------------------------------------------------------COPY--chown=builder:builder mvnw ./COPY--chown=builder:builder .mvn .mvnCOPY--chown=builder:builder pom.xml ./RUN--mount=type=cache,target=/home/builder/.m2,uid=${BUILDER_UID},gid=${BUILDER_GID}\./mvnw--batch-mode dependency:resolve# ------------------------------------------------------------# Layer: Build# ------------------------------------------------------------COPY--chown=builder:builder src ./srcRUN--mount=type=cache,target=/home/builder/.m2,uid=${BUILDER_UID},gid=${BUILDER_GID}\./mvnw--batch-mode-Pjvm-DskipTests clean verify# ============================================================# Stage 2: Runtime Environment# ============================================================# Distribute using a slim JRE-only image. Note: We do not require# the UID to match the builder; we only need a non-root user.FROM eclipse-temurin:25-jre-noble AS stage-runtimeLABEL maintainer="Emmanuel Bruno <emmanuel.bruno@univ-tln.fr>"LABEL description="Java Hello World Application - multi-stage runtime"RUNgroupadd-r appgroup &&useradd-r-g appgroup appuser &&\mkdir-p /app &&chown-R appuser:appgroup /app# Deploy minimal runtime artifacts from the build stageCOPY--from=stage-build--chown=appuser:appgroup /app/target/hello-world-*-SNAPSHOT.jar /app/app.jarCOPY--from=stage-build--chown=appuser:appgroup /app/target/libs /app/libsUSER appuserENV HOME=/home/appuser# JVM Container Ergonomics: JAVA_TOOL_OPTIONS is natively parsed by the# JVM, enabling container-aware resource management.ENV JAVA_TOOL_OPTIONS="-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0"ENTRYPOINT ["java", "-jar", "/app/app.jar"]
[CI] audit de l'image javahello:manual non execute : hote Docker partage, aucun reseau garanti
Image minimale avec jlink (JPMS) — Expert
jlink permet de créer un runtime Java sur mesure contenant uniquement les modules nécessaires.
Avertissement
Nécessite une application modularisée (JPMS) et une analyse fine des dépendances.
Dockerfile.50.jlink
# ============================================================# Stage 1: Build Environment# Purpose: Leverage Maven to compile code and "slice" a# custom JRE using the jlink toolchain.# ============================================================FROM maven:3.9.16-eclipse-temurin-25-noble AS builderWORKDIR /workspace# ------------------------------------------------------------# Layer 1: Build Infrastructure# ------------------------------------------------------------COPY .mvn/ .mvn/COPY mvnw pom.xml ./RUNchmod +x mvnw# ------------------------------------------------------------# Layer 2: Dependency Caching# ------------------------------------------------------------# Warm the Maven cache to speed up subsequent buildsRUN--mount=type=cache,target=/root/.m2\./mvnw-q dependency:go-offline# ------------------------------------------------------------# Layer 3: Application Build & JRE Slicing# ------------------------------------------------------------COPY src ./src# The 'jlink' profile triggers the maven-jlink-plugin, which# inspects the module-info and builds a minimal, custom runtime# image that contains only the required JDK modules.RUN--mount=type=cache,target=/root/.m2\./mvnw clean verify -Pjlink-DskipTests# ============================================================# Stage 2: Runtime Environment (Ubuntu Noble)# Purpose: Deploy the custom, modularized Java runtime.# ============================================================FROM ubuntu:nobleLABEL maintainer="Emmanuel Bruno <emmanuel.bruno@univ-tln.fr>"LABEL description="Java Hello World Application with Custom JRE via jlink"# Security: Create a non-privileged user to run the applicationRUNgroupadd-r appgroup &&useradd-r-g appgroup appuser &&\mkdir-p /jre &&chown-R appuser:appgroup /jre# ------------------------------------------------------------# Deployment: Copy the custom runtime# ------------------------------------------------------------# The custom JRE includes the application logic, dependencies,# and the native launcher ('app') generated during the build.COPY--from=builder--chown=appuser:appgroup /workspace/target/maven-jlink/classifiers/runtime-image/ /jre/USER appuser# JVM Container Ergonomics: JAVA_TOOL_OPTIONS is natively parsed by# the JRE, ensuring resource limits are applied to the custom runtime.ENV JAVA_TOOL_OPTIONS="-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0"# Execution: Invoke the native binary created by jlink.# No 'java -jar' command is needed, as the application is now a# self-contained modular executable.ENTRYPOINT ["/jre/bin/app"]
[CI] audit de l'image javahello:jlink non execute : hote Docker partage, aucun reseau garanti
jlink-alpine — Minimalité et compromis
jlink-alpine propose un runtime Java construit sur Alpine (musl) contenant uniquement les modules nécessaires. C’est une excellente option pédagogique pour montrer l’impact du runtime sur la taille d’image, mais elle comporte des limites pratiques.
Avertissement
Alpine utilise musl (libc alternative). Les composants natifs (JNI), certaines bibliothèques précompilées ou des outils attendus par glibc peuvent ne pas fonctionner. Testez systématiquement avant production.
Avantages:
Image très compacte (gain de plusieurs dizaines à centaines de MB).
Idéale pour démonstrations et environnements contrôlés.
Inconvénients:
Compatibilité native réduite (JNI, agents natifs, certains drivers).
Parfois plus difficile à déboguer (outils absents dans l’image).
Commandes utiles (exemples étudiants) :
Recommandation : pour un déploiement robuste, préférez jlink (Debian/distroless) sauf si vous maîtrisez l’ensemble des dépendances natives.
Exécutable natif avec GraalVM — Culture
GraalVM compile Java en binaire natif.
Avantage : Démarrage instantané (< 100ms) et RAM dérisoire.
Inconvénient : Build complexe et perte de certaines capacités dynamiques de la JVM.
Dockerfile.60.graalvm
# syntax=docker/dockerfile:1# Layer 1 — GraalVM Native Image toolchain# ============================================================================# GraalVM + native-image (the "native" toolchain, installed on top of the JDK)ARG GRAALVM_VERSION=25FROM ghcr.io/graalvm/native-image-community:${GRAALVM_VERSION} AS builderWORKDIR /workspace# Maven wrapper + POM first (re-uses the /root/.m2 cache for dependency download)COPY .mvn/ .mvn/COPY mvnw pom.xml ./RUNchmod +x mvnwRUN--mount=type=cache,target=/root/.m2\./mvnw-q-Pnative dependency:go-offline# Cap the native-image build heap so the CI render stays within the runner# memory budget (large pool: 24 Gi cgroup limit). JAVA_TOOL_OPTIONS is read by# every JVM in the build (maven + native-image analysis); -Xmx8G leaves headroom# for the native compiler + GC + runtime within the limit.ENV JAVA_TOOL_OPTIONS=-Xmx8GCOPY src ./srcRUN--mount=type=cache,target=/root/.m2\./mvnw-Pnative-DskipTests package# Layer 2 — minimal runtimeFROM gcr.io/distroless/base-debian12:nonroot AS runtimeWORKDIR /workspace# Copy the compiled native executable from the builder stageCOPY--from=builder /workspace/target/*-runner /app# The native executable is self-contained (no JVM needed at runtime).# Run as the nonroot user (uid 65532) provided by the distroless base image.USER nonroot:nonrootENTRYPOINT ["/app"]EXPOSE 8080# -----------------------------------------------------------------------------# Layer 3 — optional: multi-stage variant (for the "advanced" lesson)# -----------------------------------------------------------------------------# In a real project you'd split build + runtime more aggressively. Here we show# the same idea with a single GraalVM image used for both stages, to keep the# lesson focused on the toolchain rather than image optimisation.FROM ghcr.io/graalvm/native-image-community:${GRAALVM_VERSION} AS build-and-runWORKDIR /workspaceCOPY .mvn/ .mvn/COPY mvnw pom.xml ./RUNchmod +x mvnwCOPY src ./srcRUN--mount=type=cache,target=/root/.m2\./mvnw-Pnative-DskipTests packageCMD ["./target/*-runner"]
[CI] audit de l'image javahello:graalvm non execute : hote Docker partage, aucun reseau garanti
Comparaison des stratégies
Image Tag
Build Cold
Size
Peak RAM
Surface d’Attaque
mavenimage
28s
928MB
86.01 MiB
Maximale
mavenimagestage
24s
406MB
71.97 MiB
Moyenne
jlink-alpine
30s
163MB
55.83 MiB
Faible
graalvm
57s
46MB
5.02 MiB
Minimale
Conclusion
ImportantPoints clés pour la mise en production
Multi-stage build : Séparation build / runtime.
Utilisateur non-root : Sécurité de l’hôte.
Gestion des ressources : Paramétrage JVM pour les limites de conteneur.
Logs : Toujours sur stdout/stderr (laissé à la charge de l’orchestrateur).
Prochaine étape : orchestrer ces images avec Docker Compose.
Politique de production
Cette page dit comment ce support est produit. Son existence dans la configuration partagée est la condition d’émission du cartouche « À propos de ce support », et son texte est publié en fin de chaque leçon.
Transparence
Le support est rédigé avec l’assistance d’un modèle de langage, relu et validé par l’auteur.
Traçabilité
Chaque leçon indique en fin de document le dépôt source, la branche ou la version qui a produit la page, le commit de la leçon et l’engagement (commit) de la configuration partagée _quarto-utils. Les références sont des liens cliquables ; une information inconnue au rendu est masquée, jamais inventée.
Dates et erreurs
Aucune date d’enseignement n’est publiée sans saisie de l’auteur. Une démonstration qui échoue se voit ; une démonstration impossible fait rougir la publication plutôt que de publier une page muette.
Auteur : Emmanuel Bruno — Université de Toulon. Licence : CC BY-NC 4.0.