Building and Deploying Spring AI Applications with Docker and Kubernetes

Deploying Spring AI applications with Docker and Kubernetes packages the Java runtime, Spring Boot orchestration layer, and external AI infrastructure (cloud LLM APIs, local inference engines like Ollama or Docker Model Runner, vector databases, and observability stacks) into portable, scalable cloud-native workloads.

1. Containerizing Spring AI Applications with Docker

Spring AI applications compile into standard Spring Boot executables, allowing them to leverage modern Java containerization optimizations while addressing AI-specific runtime characteristics:
  • Image Build Strategies:

    • Cloud Native Buildpacks (spring-boot:build-image): Generates production-ready OCI container images without maintaining a Dockerfile, automatically configuring container-aware JVM memory ergonomics, layered JAR caching, and minimal base OS images.

    • Multi-Stage Dockerfiles: Separates the Maven/Gradle compilation stage from a lean, non-root runtime stage (such as Eclipse Temurin or BellSoft Liberica JRE on Alpine/Ubuntu Jammy) using Spring Boot’s layered JAR structure so dependency layers stay cached across frequent prompt or business-logic rebuilds.

  • AI-Specific Container Runtime Considerations:

    • Externalized Secrets & Configuration: Never bake LLM API keys (OPENAI_API_KEY, GEMINI_API_KEY, ANTHROPIC_API_KEY) into Docker images; inject them at runtime via environment variables or mounted secret volumes.

    • In-Process Model Caches (ONNX / Tokenizers): When using in-JVM ONNX embedding models or jtokkit tokenizers, pre-warm or mount model cache directories into the container image so pods do not repeatedly download model weights on every container restart.

    • Java 21+ Virtual Threads: Enabling Virtual Threads in containerized Spring AI services allows modest CPU/RAM container allocations to handle high-concurrency, I/O-bound LLM API streams and vector searches without spawning heavy OS threads.

2. Local Multi-Container Stack with Docker Compose & Docker Model Runner

Before deploying to Kubernetes, Docker Compose and Docker Model Runner replicate the full production topology locally:
  • Docker Model Runner Integration: Docker Desktop and Docker Engine natively pull and serve open-weight models (distributed as OCI artifacts under Docker Hub’s ai/ namespace, such as ai/gemma3, ai/llama3.1, or ai/mxbai-embed-large) over a local OpenAI-compatible HTTP endpoint—allowing Spring AI containers to run chat and embedding inference locally with zero external API keys.

  • Unified docker-compose.yml Topology: Orchestrates the Spring AI backend container alongside stateful infrastructure containers—such as PostgreSQL (pgvector), Redis Stack, MongoDB, or Ollama (with optional NVIDIA GPU passthrough)—connected over an isolated bridge network with health-checked startup ordering.

3. Kubernetes Deployment Architecture

In Kubernetes, a production Spring AI system separates stateless AI orchestration pods from stateful vector stores and self-hosted inference workloads:

Kubernetes Resource Role in a Spring AI Deployment Key Configuration Details
Deployment (Spring AI App) Runs stateless replicas of the Spring Boot AI service handling ChatClient requests, RAG orchestration, and MCP clients. Configures rolling updates, graceful shutdown (terminationGracePeriodSeconds: 60 to let active SSE streams finish), and resource requests/limits.
ConfigMap & Secret Decouples prompt/model configuration from container images. Stores application-prod.yml overrides, vector store endpoints, and model names in ConfigMaps, while injecting API keys and DB credentials from encrypted Secrets (or External Secrets Operator).
Service & Ingress / Gateway API Exposes REST and real-time streaming endpoints (text/event-stream). Disables proxy response buffering (e.g., nginx.ingress.kubernetes.io/proxy-buffering: "off") and extends read timeouts so token-by-token SSE streams flow without buffering delays.
StatefulSet / Managed Cloud DB Hosts persistent Vector Databases (pgvector, Qdrant, Redis) and relational ChatMemory storage. Backed by PersistentVolumeClaims (PVCs) or managed cloud database services for durable index retention across pod restarts.
GPU Node Pool (Deployment / KServe / Ollama) Optional dedicated nodes for self-hosted open-weight LLMs and embedding models. Uses node selectors, taints/tolerations, and [nvidia.com/gpu](https://nvidia.com/gpu) resource limits to isolate compute-heavy model inference from lightweight Spring Boot API pods.

4. Health Probes, Scaling & Observability in Kubernetes

AI workloads exhibit markedly different latency and resource profiles than traditional CRUD microservices, requiring tuned Kubernetes lifecycle settings:
  • Startup, Liveness, and Readiness Probes (Spring Boot Actuator):

    • Startup Probe: Gives slow-initializing containers extra time if they load local ONNX embeddings or validate vector store schemas at boot.

    • Readiness Probe (/actuator/health/readiness): Ensures Kubernetes routes traffic only after database pools and vector store connections are ready.

    • Liveness Probe (/actuator/health/liveness): Keep lightweight and decoupled from external LLM API health—if an external provider (Gemini or Claude) experiences transient latency, failing the pod’s liveness probe would trigger destructive cascading pod restarts.

  • Horizontal Pod Autoscaling (HPA & KEDA):

    • Traditional CPU-based HPA often fails to scale Spring AI pods because threads spend most of their time waiting on external LLM network I/O rather than burning local CPU.

    • Production deployments scale pods using custom Prometheus metrics via KEDA—triggering scale-out based on active concurrent HTTP/SSE connections, request queue depth, or gen_ai request rates.

  • Kubernetes-Native Observability:

    • Spring AI exports OpenTelemetry (OTLP) traces and Prometheus metrics directly to cluster observability stacks (OpenTelemetry Collector, Prometheus, Grafana, Tempo, or OpenLIT Helm charts) to monitor per-pod token consumption, model latency, and vector query health.

5. Production Best Practices

  • Disable Proxy Buffering on Ingress & Service Meshes: Ingress controllers (NGINX, Envoy, Istio) buffer HTTP responses by default, which breaks real-time .stream() Server-Sent Events by holding tokens until completion; explicitly disable buffering and increase idle timeouts to 120+ seconds on streaming routes.

  • Isolate Ingestion Workers from Interactive Chat Pods: Run heavy document ETL pipelines (PDF parsing, chunking, batch embedding generation) as separate Kubernetes Jobs, CronJobs, or dedicated worker deployments so bulk ingestion memory spikes never degrade latency for live user chat pods.

  • Package Deployments with Helm or Kustomize: Manage environment-specific differences (local Minikube/Kind with Ollama vs. staging/production EKS/GKE/AKS with cloud models and managed pgvector) using Helm charts or Kustomize overlays.

Scroll to Top