Docker & deployment for Java
Containerise a Spring Boot app and run it with its database.
By Invicly Tech, , in Backend Java Development. About 10 minutes to read.
In short
Docker packages your Spring Boot jar and a Java runtime into one image that runs the same everywhere. A multi-stage build compiles with a JDK but ships only a smaller JRE image.
Explained simply
Docker puts your application and everything it needs to run into one package called an image. For a Spring Boot app that means a Java runtime plus your jar file. Anyone with Docker can run that image and get the same result, on a laptop, a CI server or a cloud machine.
A running copy of an image is a container. It is an isolated process with its own files and network, but it shares the host's kernel, so it starts in seconds and uses far less memory than a virtual machine.
The recipe for an image is a Dockerfile. Each line adds a layer, and Docker caches layers it has built before. If you order the lines well, a code change rebuilds only the small part that changed, and builds take seconds instead of minutes.
Real apps need a database too. Docker Compose starts several containers from one YAML file: your app and Postgres, on a shared network, with the right settings. One command, docker compose up, gives every developer the same working setup.
Press Play on a diagram to walk through it one step at a time.
- 1Build stage
JDK image with Maven wrapper
- 2Package jar
./mvnw package produces the fat jar
- 3Runtime stage
Fresh, smaller JRE image
- 4Copy jar only
No source code or build tools shipped
- 5Run container
docker compose up with Postgres
- 1Application classes
Changes on almost every commit
- 2Snapshot dependencies
Changes sometimes
- 3Spring Boot loader
Rarely changes
- 4Dependencies
Third-party jars, cached between builds
- 5Base JRE image
eclipse-temurin:21-jre
- One 50 MB layer
- Every commit rebuilds all of it
- Slow pushes and pulls
- Simplest Dockerfile
- Dependencies cached separately
- A commit rebuilds about 200 KB
- Fast pushes and deploys
- A few more Dockerfile lines
In depth
Why layer order matters
Docker builds a Dockerfile top to bottom. For each step it checks whether it already has a cached layer for the same instruction and the same input files. The first step whose inputs changed, and every step after it, must be rebuilt.
A Spring Boot fat jar holds about 50 MB of dependencies and maybe 200 KB of your own code. If you copy that jar in one step, every code change creates a whole new 50 MB layer to build, push and pull. Spring Boot can split the jar into layers ordered from least to most changing: dependencies, spring-boot-loader, snapshot-dependencies, application. Copy them in that order and a normal commit only rebuilds the tiny application layer.
The same idea applies in the build stage: copy pom.xml and download dependencies before copying src, so Maven does not download the internet on every change.
Extracting layers with Spring Boot 3.3 and later
Spring Boot 3.3 replaced the old layertools jar mode with a new tools mode. The command java -Djarmode=tools -jar app.jar extract --layers --destination extracted unpacks the jar into one folder per layer. Inside the application layer is a small application.jar that points at the libraries, so the final image still starts with java -jar application.jar.
There is also a zero-Dockerfile option: ./mvnw spring-boot:build-image (or bootBuildImage in Gradle) uses Cloud Native Buildpacks to produce a layered, non-root image with a tuned JVM memory calculator. It is a good default if you do not need a custom Dockerfile.
Whichever route you take, pick a base image with only a JRE, such as eclipse-temurin:21-jre, and pin the tag so builds are repeatable.
- 1Stage 1: JDK
Copy pom.xml, download dependencies, then copy src
- 2Build the jar
./mvnw package produces the fat jar
- 3Extract layers
jarmode=tools extract --layers
- 4Stage 2: JRE
Copy four layer folders, slowest-changing first
- 5Run as non-root
java -jar application.jar
Running Java well inside a container
Modern JVMs (Java 11 and later) read the container's memory and CPU limits. By default the maximum heap is only 25% of the container's memory, which wastes most of a 1 GB container. Set -XX:MaxRAMPercentage=75.0 through JAVA_TOOL_OPTIONS so the heap uses most of the limit while leaving room for metaspace, threads and buffers.
Run as a normal user, not root: create one in the Dockerfile and switch with USER. Use the exec form of ENTRYPOINT (a JSON array) so java is PID 1 and receives the SIGTERM that Docker sends on stop. Spring Boot 3.4 and later enable graceful shutdown by default, so in-flight requests finish before the app exits.
Keep configuration out of the image. Spring Boot maps environment variables to properties, so SPRING_DATASOURCE_URL overrides spring.datasource.url without rebuilding.
- JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=75.0
- Exec form: ENTRYPOINT ["java", "-jar", "application.jar"]
- Add a .dockerignore with target/ and .git/
Compose: app plus database, started in the right order
In Compose every service joins a shared network and can reach the others by service name. Your app connects to jdbc:postgresql://db:5432/app, not localhost, because inside the app container localhost is the app itself.
depends_on alone only waits for the database container to start, not for Postgres to accept connections. Add a healthcheck to the database (pg_isready) and use depends_on with condition: service_healthy, so the app starts once the database is ready.
Store database files in a named volume so data survives docker compose down. Use docker compose down -v only when you really want to wipe it. Keep passwords in an .env file that is not committed; Compose reads it automatically for variable substitution.
Learn it in 3 short steps
About 1h each. Track them with a timer in your plan.
- 1Write a multi-stage Dockerfile for Spring Boot~1h
- 2Build layered jars for faster builds~1h
- 3Run app and database with Compose~1h
Key points
- Multi-stage builds keep compilers and source out of the final image.
- Layered jars put rarely changing dependencies in early, cached layers.
- Pass configuration through environment variables, not baked-in files.
- In Compose, services reach each other by service name, e.g. jdbc:postgresql://db:5432/app.
Key terms
Tap a card to flip it. 0/5 known
Examples
FROM eclipse-temurin:21-jdk AS build
WORKDIR /app
COPY . .
RUN ./mvnw -q package -DskipTests
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]Build with docker build -t my-api . and run with docker run -p 8080:8080 my-api
A layered, non-root Dockerfile
Stage 1 downloads dependencies before copying source, builds the jar and extracts its layers. Stage 2 starts from a JRE image, creates a non-root user and copies the four layers in two steps, slowest-changing first. Build it twice, change one Java file, and build again: only the last COPY and the Maven steps rerun.
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw -q dependency:go-offline
COPY src src
RUN ./mvnw -q package -DskipTests && cp target/*.jar app.jar \
&& java -Djarmode=tools -jar app.jar extract --layers --destination out
FROM eclipse-temurin:21-jre
RUN useradd --system --uid 1001 spring
USER spring
WORKDIR /app
COPY --from=build /src/out/dependencies/ /src/out/spring-boot-loader/ ./
COPY --from=build /src/out/snapshot-dependencies/ /src/out/application/ ./
ENTRYPOINT ["java", "-jar", "application.jar"]App and Postgres with a health-gated start
Compose builds the app from the Dockerfile, starts Postgres with a named volume, waits until pg_isready succeeds, then starts the app with its datasource set by environment variables. Run docker compose up --build and open localhost:8080.
services:
db:
image: postgres:17
environment: { POSTGRES_DB: app, POSTGRES_USER: app, POSTGRES_PASSWORD: secret }
volumes: [pgdata:/var/lib/postgresql/data]
healthcheck: { test: ["CMD", "pg_isready", "-U", "app"], interval: 5s, retries: 10 }
api:
build: .
ports: ["8080:8080"]
environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/app
SPRING_DATASOURCE_USERNAME: app
SPRING_DATASOURCE_PASSWORD: secret
JAVA_TOOL_OPTIONS: -XX:MaxRAMPercentage=75.0
depends_on: { db: { condition: service_healthy } }
volumes: { pgdata: {} }Quick reference
- Copy pom.xml and fetch dependencies before copying src to keep the cache warm
- java -Djarmode=tools -jar app.jar extract --layers --destination out (Boot 3.3+)
- ./mvnw spring-boot:build-image builds a layered image with buildpacks, no Dockerfile
- The JVM uses 25% of container memory for heap by default; set MaxRAMPercentage
- Inside Compose, reach the database by service name (db), not localhost
- depends_on with condition: service_healthy waits for a passing healthcheck
- docker image history my-api shows each layer and its size
Common mistakes
- Shipping the full JDK and source code in the runtime image.
- Using localhost for the database inside a container instead of the service name.
- Copying all source before dependencies, so every change re-downloads them.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Build the image, then use docker image history to find the largest layer and explain what is in it.
- Exercise 2medium
Prove the layer cache works: build, change one line in a controller, rebuild, and note which steps say CACHED.
- Exercise 3hard
Make the app container report healthy only when Spring Boot is ready, and make Compose restart it if it crashes.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use Alpine images for Java?
- You can, but Alpine uses musl instead of glibc, and some native libraries behave differently. Debian or Ubuntu based JRE images like eclipse-temurin:21-jre are the safer default.
- Dockerfile or buildpacks?
- Buildpacks (spring-boot:build-image) give a good, secure image with no Dockerfile to maintain. Write a Dockerfile when you need full control over the base image or extra tools.
- Why is my image over 500 MB?
- Usually because the runtime stage uses a full JDK image or copies the source and Maven cache. Use a JRE base and copy only the built layers.
- Can I use GraalVM native images instead?
- Yes. Spring Boot supports native images that start in milliseconds and use less memory, but builds are slower and some libraries need extra hints. Start with a normal JVM image.