Medium java docker

How do you containerize a Spring Boot app with Docker?

The 30 second answer

I build an executable jar, then a Docker image whose runtime is a JRE and a process that runs that jar. A multi-stage Dockerfile compiles in a JDK image and copies only the jar into a slimmer runtime image. Spring Boot also documents layered jars and Buildpacks, which can produce the image without a hand-written Dockerfile.

Could you say this in an interview?

The straightforward path is: build the Boot jar, copy it into an image that has a Java runtime, and set the container command to java -jar. A multi-stage build keeps the JDK and Maven or Gradle out of the final image.

FROM eclipse-temurin:21-jdk-alpine AS build
WORKDIR /src
COPY . .
RUN ./mvnw -q -DskipTests package

FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=build /src/target/orders-1.0.0.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app/app.jar"]

The official Spring Boot documentation also describes Buildpacks (./mvnw spring-boot:build-image) and layered jars, which make rebuilds and memory use more efficient than copying one fat jar. The process in the container should be the JVM, not a wrapper that ignores SIGTERM.

Alternate interview scenarios

"What is Docker compose? Multi-stage Docker builds?"

Docker Compose runs several containers from one file (the app, a database, a broker) for local or simple deployments. A multi-stage Docker build compiles in a JDK image and copies only the runtime jar into a slimmer JRE image, which is the usual way I containerise a Spring Boot app.

# compose, local only
services:
  app:
    build: .
    ports: ["8080:8080"]
  db:
    image: postgres:16-alpine
FROM eclipse-temurin:21-jdk-alpine AS build
# ... ./mvnw package
FROM eclipse-temurin:21-jre-alpine
COPY --from=build /src/target/app.jar /app/app.jar

Compose is not a substitute for Kubernetes in production at most companies, and a single-stage image that ships Maven and the source is not the image I want to run.

Sources (2)
  1. Spring Boot: container imagesdocs.spring.io
  2. Spring Boot: Dockerfilesdocs.spring.io