Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 119 ยท Architecture and Deployment

Docker for Java Developers

Package Java and Spring Boot apps with Docker - multi-stage Dockerfiles, layered JARs, docker compose with PostgreSQL, JVM memory and CPU limits, and graceful shutdown.

"It works on my machine" used to be a joke with real costs: a different JDK version on the server, a missing environment variable, a database configured differently. Docker removes most of that variation. You package your application together with its runtime (the JDK, system libraries, configuration defaults) into an image, and that exact image runs on your laptop, in CI and in production.

For Java developers Docker matters in two ways. You ship your services as container images, which is how almost every modern platform (Kubernetes, cloud container services) wants them. And you use containers during development: a real PostgreSQL, Kafka or Redis starts with one command and disappears when you're done. In this lesson you will write a production-quality Dockerfile for a Spring Boot application, run it with a database using Docker Compose, and learn how the JVM behaves inside a container, which is where most Java-specific container problems come from.

Docker itself can't run in this course's sandbox, so Docker commands and files are shown read-only. The runnable examples show what your Java program sees inside a container: memory and CPU limits, environment variables, and shutdown signals. You set up Docker Desktop in Setting Up a Java Development Environment.

Images, containers and registries

  • An image is a read-only template: a stack of filesystem layers plus metadata (the command to run, environment variables, exposed ports). Images are built from a Dockerfile.
  • A container is a running instance of an image, with its own isolated filesystem, process tree and network. You can start many containers from one image. A container is not a virtual machine: it shares the host's kernel and starts in milliseconds.
  • A registry stores images: Docker Hub, GitHub Container Registry, or your cloud provider's registry. Images are named registry/repository:tag, for example ghcr.io/acme/library-service:1.4.2.

Each instruction in a Dockerfile that changes files creates a layer. Layers are cached and shared: if a layer and everything below it are unchanged, Docker reuses it instead of rebuilding or re-uploading it. Ordering your Dockerfile so that rarely-changing layers come first is the main trick for fast builds.

A tag such as 1.4.2 or latest can be moved to a different image later. For deployments, reference the image's immutable digest (library-service@sha256:...) or at least never reuse a version tag. Never deploy latest.

A first Dockerfile

Assume ./mvnw package (see Maven in Depth) produced target/library-service-1.4.2.jar, an executable Spring Boot JAR. The simplest Dockerfile is:

DOCKERFILE
FROM eclipse-temurin:25-jre
WORKDIR /app
COPY target/library-service-1.4.2.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
  • FROM picks the base image. eclipse-temurin is a widely used OpenJDK build; the -jre variant has only the runtime, which is smaller than the full JDK.
  • COPY adds your JAR as a new layer.
  • EXPOSE documents the port; it doesn't publish it.
  • ENTRYPOINT in the JSON array (exec) form runs java directly as process 1 of the container. This matters for shutdown signals, as you will see.

Build and run it:

Terminal
docker build -t library-service:1.4.2 .
docker run --rm -p 8080:8080 -e SPRING_PROFILES_ACTIVE=prod library-service:1.4.2
docker ps                                   # running containers
docker logs -f <container-id>               # follow stdout
docker exec -it <container-id> sh           # a shell inside the container

-p 8080:8080 maps host port 8080 to the container's port 8080; -e sets an environment variable.

This works, but it has two problems. The JAR is built outside Docker, so the build depends on whatever JDK and Maven the build machine has. And the whole 40 MB fat JAR is one layer: change one line of your code, and the entire layer, including all dependencies, has to be rebuilt, pushed and pulled again.

A multi-stage Dockerfile with layered JARs

A multi-stage build uses one image with the full JDK and Maven to compile, and a second, slim image to run. Only the files you copy explicitly reach the final image.

Spring Boot also knows how to split its fat JAR into layers ordered by how often they change: third-party dependencies (change rarely), the spring-boot-loader, snapshot-dependencies, and your application classes (change on every commit). With Boot 3.3 and later, the tools jar mode extracts them:

DOCKERFILE
# syntax=docker/dockerfile:1

# ---------- build stage ----------
FROM eclipse-temurin:25-jdk AS build
WORKDIR /workspace

# 1. Dependencies first: this layer is cached until pom.xml changes.
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN --mount=type=cache,target=/root/.m2 ./mvnw -q dependency:go-offline

# 2. Then the source code.
COPY src src
RUN --mount=type=cache,target=/root/.m2 ./mvnw -q package -DskipTests

# 3. Split the fat JAR into layers.
RUN java -Djarmode=tools -jar target/*.jar extract --layers --launcher --destination extracted

# ---------- runtime stage ----------
FROM eclipse-temurin:25-jre
RUN groupadd --system app && useradd --system --gid app --no-create-home app
USER app
WORKDIR /app

COPY --from=build /workspace/extracted/dependencies/ ./
COPY --from=build /workspace/extracted/spring-boot-loader/ ./
COPY --from=build /workspace/extracted/snapshot-dependencies/ ./
COPY --from=build /workspace/extracted/application/ ./

ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75"
EXPOSE 8080
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]

What each detail buys you:

  • Reproducible builds: the JDK version is pinned in the Dockerfile, not taken from the build machine.
  • Fast rebuilds: the dependency:go-offline layer and the --mount=type=cache Maven cache mean a code change doesn't re-download the internet.
  • Small, cache-friendly pushes: when only your code changed, only the thin application layer (often a few hundred kilobytes) is new. The 40 MB of dependencies is already in the registry and on the servers.
  • Non-root user: if an attacker breaks into the process, they aren't root inside the container.
  • No build tools in production: the runtime image has no Maven, no compiler and no source code.

Add a .dockerignore file so target/, .git/, IDE folders and local secrets aren't sent to the build:

TEXT
target/
.git/
.idea/
*.iml
.env

Alternatives to writing a Dockerfile

  • Cloud Native Buildpacks: ./mvnw spring-boot:build-image (or ./gradlew bootBuildImage) builds a layered, non-root, well-configured image without any Dockerfile, including JVM memory tuning.
  • Jib (a Maven/Gradle plugin from Google) builds optimized images directly from your build, without even needing Docker installed.

Both are excellent choices. Knowing how the Dockerfile above works helps you understand and debug what they generate.

The JVM inside a container

A container's limits come from Linux cgroups: "at most 1 GB of memory, at most 2 CPUs". Since JDK 10 (and 8u191), the JVM reads these limits (-XX:+UseContainerSupport, on by default) instead of the host's resources. The JVM then picks its defaults from them:

  • Maximum heap: by default 25% of the memory limit (50% for very small containers, under about 250 MB). In a 1 GB container that is only 256 MB of heap, which surprises many people.
  • CPU count: Runtime.availableProcessors() reflects the CPU limit. It sizes the garbage collector's threads, the common ForkJoinPool and many framework thread pools.
  • Garbage collector: with fewer than 2 CPUs or less than about 1.8 GB of memory, the JVM considers the machine a "client" and chooses the Serial collector instead of G1.

This program prints what the JVM decided. Run it and compare the values with the server it runs on:

Java What the JVM sees: memory, CPUs and GC

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the last line. Our code runner is itself a small sandbox, and it passes explicit options: one processor, the Serial collector and a 256 MB maximum heap (the JVM reports slightly less as usable). That is exactly the kind of tuning you do for your own containers through JAVA_TOOL_OPTIONS. Without such flags, ActiveProcessorCount shows -1 ("detect from the container") and the JVM derives the heap from MaxRAMPercentage.

Setting memory correctly

The container's memory limit must hold the whole JVM, not just the heap: heap + metaspace (class metadata) + code cache (JIT-compiled code) + thread stacks + direct buffers (Netty, NIO) + GC overhead. If the total exceeds the limit, the kernel kills the process instantly. There is no OutOfMemoryError and no stack trace; the container just exits with code 137 and Kubernetes reports OOMKilled.

Practical rules:

  • Prefer percentages over fixed sizes, so the heap follows the container limit: -XX:MaxRAMPercentage=75 is a common starting point for typical services, leaving 25% for everything else. Lower it (60โ€“70%) for apps with many threads or heavy direct-buffer use.
  • Pass options with the JAVA_TOOL_OPTIONS environment variable. The JVM reads it automatically, so you can change memory settings per environment without rebuilding the image.
  • Set the memory request and limit to the same value in Kubernetes for JVM services, so the heap size computed at startup stays valid.
  • Watch jvm.memory.used and container memory metrics together (Actuator, Metrics and Observability).
Terminal
docker run --rm --memory=1g --cpus=2 \
  -e JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError" \
  library-service:1.4.2

-XX:+ExitOnOutOfMemoryError makes the JVM exit on a heap OutOfMemoryError instead of limping along half-broken, so the platform restarts it cleanly.

CPU limits

CPU limits are a quota of CPU time, not dedicated cores. A container with --cpus=0.5 sees one processor. If your container is limited to one CPU, the JVM picks Serial GC and frameworks create small thread pools; that may be fine for a tiny service but hurts throughput for a busy one. Give JVM services at least 2 CPUs when you can, or set -XX:ActiveProcessorCount=2 and an explicit GC (-XX:+UseG1GC) if you know what you are doing.

Configuration through environment variables

An image should be the same in every environment; only configuration differs. The standard way to pass configuration into a container is environment variables (and, for secrets, mounted files). Spring Boot reads them with relaxed binding: SPRING_DATASOURCE_URL sets spring.datasource.url, and LIBRARY_LOANS_MAXPERMEMBER sets library.loans.max-per-member (Configuration, Properties and Profiles).

The example reads settings from the environment with defaults, the way a container-friendly app does, and shows the conversion from property names to environment variable names:

Java Container-style configuration from environment variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

None of the variables are set here, so the defaults are used; in a container you would pass -e SERVER_PORT=9000 or define them in a Compose file or Kubernetes manifest. Never bake secrets (database passwords, API keys) into the image: anyone who can pull the image can read every layer. Inject them at runtime from a secret store.

Graceful shutdown and PID 1

When Docker or Kubernetes stops a container, it sends SIGTERM to process 1, waits a grace period (10 seconds for docker stop, 30 seconds by default in Kubernetes), and then sends SIGKILL, which can't be caught. Your application should use that window to stop accepting new requests, finish in-flight ones, and close connections.

The JVM turns SIGTERM into an orderly shutdown and runs shutdown hooks. Spring Boot registers one that closes the application context; with server.shutdown=graceful (the default since Boot 3.4), the web server first stops taking new requests and waits for active ones, up to spring.lifecycle.timeout-per-shutdown-phase (30 seconds by default). Keep that below the platform's grace period.

The example registers a shutdown hook that drains an HttpServer, then triggers shutdown with System.exit, which runs hooks the same way a SIGTERM does:

Java A shutdown hook that drains in-flight requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The request that was already running completed with 200 before the hook finished, because server.stop(2) waited for it. Without the hook, the client would have seen a broken connection.

All of this only works if java is process 1 and receives the signal. The shell form ENTRYPOINT java -jar app.jar (without brackets) starts /bin/sh -c "java -jar app.jar". The shell becomes process 1, doesn't forward SIGTERM to Java, and after the grace period everything is SIGKILLed: no graceful shutdown, every stop takes the full timeout. Use the exec form ["java", ...], or exec java ... inside a wrapper script.

Docker Compose for local development

Docker Compose describes several containers in one YAML file and starts them together. Here is the library service with PostgreSQL:

YAML
# compose.yaml
services:
  db:
    image: postgres:18
    environment:
      POSTGRES_DB: library
      POSTGRES_USER: library
      POSTGRES_PASSWORD: dev-only-password
    ports:
      - "5432:5432"                         # so your IDE can connect too
    volumes:
      - db-data:/var/lib/postgresql        # data survives container restarts
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U library -d library"]
      interval: 5s
      timeout: 3s
      retries: 10

  app:
    build: .
    depends_on:
      db:
        condition: service_healthy          # wait until PostgreSQL accepts connections
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/library
      SPRING_DATASOURCE_USERNAME: library
      SPRING_DATASOURCE_PASSWORD: dev-only-password
      JAVA_TOOL_OPTIONS: -XX:MaxRAMPercentage=75
    ports:
      - "8080:8080"

volumes:
  db-data:
Terminal
docker compose up -d --build     # build the app image, start both containers
docker compose logs -f app       # follow the app's logs
docker compose ps                # status, including health
docker compose down              # stop and remove containers (add -v to delete the volume too)

Inside the Compose network, containers reach each other by service name: the app connects to db:5432, not localhost. Inside a container, localhost means the container itself, which is the most common Compose mistake. (Recent official PostgreSQL images, version 18 and later, keep data under /var/lib/postgresql; older ones used /var/lib/postgresql/data.)

For day-to-day development you often run only the database in Docker and the app in your IDE. Spring Boot's spring-boot-docker-compose module can even start compose.yaml automatically when the app starts and configure the datasource from it. For tests, Testcontainers starts throwaway containers from JUnit, as described in Integration Testing.

Smaller, safer images

  • Use a JRE or a custom runtime. eclipse-temurin:25-jre is much smaller than the JDK image. jlink can build a runtime with only the modules your app uses; distroless or Alpine-based images shrink it further (test Alpine carefully: it uses musl instead of glibc).
  • Run as a non-root user, as in the Dockerfile above.
  • Pin base image versions and rebuild regularly to pick up security patches. Scan images in CI with a tool such as Trivy, Grype or Docker Scout.
  • Add a health check endpoint (Actuator's /actuator/health/liveness and /readiness); orchestrators use it rather than Docker's HEALTHCHECK.
  • Speed up startup with class data sharing: Spring Boot 3.3+ can train a CDS archive, and Java 24+ adds an ahead-of-time cache (-XX:AOTCache) that also stores loaded and linked classes. Deploying Java Applications also covers GraalVM native images, which start in milliseconds.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You change one line in a controller and rebuild the multi-stage, layered image. Which layers usually need to be rebuilt and pushed?

    Layers are cached in order. pom.xml didn't change, so the dependency download and the dependencies layer are reused; only the source compile and the application layer change.
  2. 2. A Spring Boot container with a 1 GB memory limit and no JVM options shows a maximum heap of about 256 MB. Why?

    MaxRAMPercentage defaults to 25. Set it explicitly, for example to 75, to use the container's memory well.
  3. 3. A container keeps exiting with code 137 and Kubernetes says OOMKilled, but there's no OutOfMemoryError in the logs. What's the most likely cause?

    The kernel kills a process over its cgroup limit without warning. Leave room for non-heap memory, for example with MaxRAMPercentage around 75.
  4. 4. A Dockerfile ends with ENTRYPOINT java -jar app.jar (shell form). What happens on docker stop?

    Use the exec form ["java", "-jar", "app.jar"] so the JVM is process 1, receives SIGTERM and runs its shutdown hooks.
  5. 5. In compose.yaml, the app uses SPRING_DATASOURCE_URL=jdbc:postgresql://localhost:5432/library and fails to connect. Why?

    Each container has its own network namespace. Compose services reach each other by service name on the shared network.

Summary

  • An image is a layered, read-only template; a container is a running instance; registries store images. Deploy by version or digest, never latest.
  • Use a multi-stage Dockerfile: build with the JDK, run on a JRE, copy Spring Boot's layered JAR parts so code changes produce tiny layers. Add a .dockerignore and run as non-root. Buildpacks and Jib are good alternatives.
  • The JVM respects container limits: default max heap is 25% of the memory limit, and the CPU limit drives GC choice and pool sizes. Set -XX:MaxRAMPercentage (often 75) via JAVA_TOOL_OPTIONS and leave room for non-heap memory; exit code 137 means the kernel killed the process.
  • Configure containers with environment variables (Spring's relaxed binding) and inject secrets at runtime.
  • Use the exec form ENTRYPOINT ["java", ...] so the JVM gets SIGTERM; Spring Boot shuts down gracefully within the grace period.
  • Docker Compose runs the app with PostgreSQL and other dependencies; services reach each other by name, and health checks with depends_on order startup.

Next: Deploying Java Applications takes your image to production: configuration, cloud platforms, Kubernetes, native images and CI/CD pipelines.