Sub topic 3
Building Images with Buildpacks and Deploying Them
Assume you know basic Spring Boot, Maven or Gradle, HTTP, and container concepts. This chapter focuses on the path from a built application to a deployable image.
Build an image without a Dockerfile
Cloud Native Buildpacks inspect your application and create an OCI container image. The Spring Boot plugin selects a suitable Java runtime, copies the application, and creates optimized layers. You do not need to maintain a Dockerfile.
# Maven
./mvnw spring-boot:build-image \
-Dspring-boot.build-image.imageName=myorg/myapp:1.0.0
# Gradle
./gradlew bootBuildImage --imageName=myorg/myapp:1.0.0The image can then be tested locally or pushed to a registry. Buildpacks usually provide safer defaults than a hand-written image, but a Dockerfile gives you more control over the operating system and startup command.
Size the JVM in a container
A container has CPU and memory limits. The JVM detects many container limits, but the application still needs room for heap, threads, class metadata, and native memory.
Start with a memory limit and observe actual use. Avoid setting the heap to the entire container limit. A practical starting point is to reserve part of the limit for non-heap memory, then adjust from metrics.
Deploy the image to Kubernetes
Kubernetes runs the image in a Pod. Its Deployment defines the desired number of replicas. Configuration usually comes from environment variables or ConfigMaps, while passwords come from Secrets. Readiness and liveness probes tell Kubernetes when to send traffic and when to restart a stuck process.
Set a termination grace period long enough for Spring Boot to finish active requests. A pod should become unready before it exits.
Automate build, test, and release
A CI/CD pipeline commonly performs these steps:
- Compile and run unit tests.
- Build the executable JAR.
- Build the image with Buildpacks.
- Scan and tag the image using an immutable version.
- Push it to a registry.
- Update the Kubernetes deployment.
The release should use the same artifact that passed tests. Avoid rebuilding from different source states between stages.
Consider a GraalVM native image
A native image compiles the application ahead of time into a platform-specific executable. It can start quickly and use less memory, which helps short-lived workloads and dense containers.
The trade-offs are longer builds, more difficult reflection or dynamic-proxy configuration, and less flexibility than a JVM image. Choose it when startup time or memory use matters more than build simplicity and JVM portability.
Exercise
When is a Buildpack image a better choice than a Dockerfile?
Show answer
Choose Buildpacks when you want a maintained Java runtime and repeatable defaults without managing image construction. Choose a Dockerfile when you need precise control over the base image or startup process.