Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 119 ยท Architecture and Deployment

Deploying Java Applications

Deploy Java services to production - executable JARs, environment configuration, database migrations, cloud options, Kubernetes basics, GraalVM native images and CI/CD.

Writing a service is half the job. The other half is getting it onto servers, configuring it for each environment, upgrading it without downtime, and doing all that dozens of times a week without anyone holding their breath. That is deployment, and in modern teams it is automated from the first commit.

This lesson walks the path from source code to production. You will look inside an executable JAR (and build and run one), see how a service picks up configuration per environment, apply database migrations safely, compare hosting options from a plain VM to Kubernetes, learn the Kubernetes objects every Java developer meets, weigh GraalVM native images against the regular JVM, and finish with a CI/CD pipeline that ties it all together. It builds directly on Docker for Java Developers and Actuator, Metrics and Observability.

What you deploy: the artifact

Every deployment starts with an artifact, the thing your build produces and your servers run:

Artifact What it is Typical use
Executable ("fat") JAR Your classes plus all dependencies plus a launcher, run with java -jar Spring Boot services on VMs or PaaS
Thin JAR + lib/ folder Your code separate from dependencies Custom setups, layered images
WAR A web archive deployed into an external servlet container Legacy apps on Tomcat or an application server, see Servlet Lifecycle and Deployment
Container image The JAR plus a JRE and OS libraries Kubernetes, cloud container services; today's default
Native executable Ahead-of-time compiled machine code, no JVM Fast-starting services, serverless, CLIs

A JAR is just a ZIP file with a META-INF/MANIFEST.MF. The manifest's Main-Class entry is what makes java -jar work. The following program does what Maven's package phase does on a small scale: it compiles a class with the JDK's built-in compiler API, packages it into a JAR with a manifest, inspects the result, and then launches it in a separate JVM with a system property and an environment variable, just like a server would.

Java Build, inspect and run an executable JAR

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.

Spring Boot's fat JAR adds two things to this picture: dependency JARs nested under BOOT-INF/lib/, and its own launcher as the Main-Class, which sets up a class loader for those nested JARs and then calls your @SpringBootApplication class (named in the Start-Class manifest entry).

Running a JAR on a server

On a plain Linux VM, a service is usually run by systemd, which starts it at boot, restarts it on failure, and collects its output in the journal:

INI
# /etc/systemd/system/library-service.service
[Unit]
Description=Library service
After=network-online.target

[Service]
User=library
WorkingDirectory=/opt/library-service
EnvironmentFile=/etc/library-service/env
ExecStart=/usr/bin/java -XX:MaxRAMPercentage=75 -jar /opt/library-service/library-service.jar
SuccessExitStatus=143
Restart=on-failure
TimeoutStopSec=40

[Install]
WantedBy=multi-user.target

SuccessExitStatus=143 tells systemd that exit code 143 (128 + SIGTERM's number 15) is a normal stop for a JVM. EnvironmentFile keeps configuration and secrets out of the unit file. Deploy with systemctl restart library-service after copying the new JAR.

Configuration per environment

The same artifact must run in development, staging and production. Everything that differs belongs in configuration, supplied by the environment, never compiled in. This is a key principle of the twelve-factor app methodology.

Spring Boot reads configuration from many sources and lets the more specific ones win. Simplified, from highest to lowest priority:

  1. Command-line arguments (--server.port=9000)
  2. Java system properties (-Dserver.port=9000)
  3. Environment variables (SERVER_PORT=9000)
  4. Profile-specific files (application-prod.yml) outside, then inside the JAR
  5. application.yml outside, then inside the JAR
  6. Defaults in code

The next example models this: four sources checked in order, with the winning source shown for each key. The environment is simulated with a map, since the sandbox has no interesting variables.

Java Layered configuration with profiles and overrides

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 database URL came from the environment, overriding both property files; the port came from the command line; the log level from the prod profile; and the loan limit from the defaults. Notice also that the password is masked in the output: never print secrets, not even in startup logs.

Secrets (database passwords, API keys, signing keys) never belong in Git, in images or in application.yml. Store them in a secret manager (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, Google Secret Manager) or Kubernetes Secrets, and inject them as environment variables or mounted files at runtime. Rotate them, and give each environment its own.

Database migrations

Your code and your database schema must change together. Applying SQL scripts by hand doesn't scale and eventually goes wrong in one environment. Migration tools such as Flyway and Liquibase keep versioned scripts in your repository (db/migration/V1__create_book.sql, V2__add_isbn.sql) and record which ones each database has already run in a history table. Spring Boot runs Flyway automatically at startup when flyway-core is on the classpath.

The core mechanism is small enough to build on H2: apply pending migrations in version order, record each with a checksum, skip ones already applied, and refuse to continue if an applied script was edited afterward.

Java A Flyway-style migration runner on H2

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.

Two rules follow from this mechanism: never edit a migration that has run anywhere, always add a new one; and make each migration safe to run while the previous version of the app is still serving traffic, because during a rolling deployment old and new code share the database. For breaking changes use the expand and contract pattern: first add the new column and write to both (expand), deploy code that reads the new column, then drop the old column in a later release (contract). Renaming a column in one step breaks the old instances still running.

Running migrations at app startup is convenient. In larger systems, teams often run them as a separate step in the pipeline (or a Kubernetes Job) before the new version rolls out, so a failing migration stops the deployment before any code changes.

Where to run it

Option You manage Good for
Virtual machine (Hetzner, DigitalOcean, EC2, Compute Engine) + systemd or Docker OS, JDK, patches, scaling, load balancer Small setups, full control, low cost
Platform as a Service (Heroku, Render, Railway, Azure App Service, AWS Elastic Beanstalk) Just the app and its config Teams that want simple git push or image deploys
Serverless containers (Google Cloud Run, AWS App Runner, Azure Container Apps) A container image Bursty traffic, scale to zero, little operations work
Managed Kubernetes (EKS, GKE, AKS, or a provider's cluster) Manifests, cluster add-ons Many services, platform teams, fine-grained control
Functions (AWS Lambda, Azure Functions) Individual functions Event handlers; needs fast startup (SnapStart, native images)

Whatever you choose, keep the database managed if you can (Amazon RDS, Cloud SQL, Azure Database, or a provider's managed PostgreSQL/MySQL): backups, failover and upgrades are hard to do well yourself.

Kubernetes basics

Kubernetes runs containers across a cluster of machines and keeps the actual state matching the desired state you declare in YAML. The objects you meet first:

  • Pod: one or more containers scheduled together; the smallest unit. Pods are disposable and get new IPs when replaced.
  • Deployment: "keep 3 replicas of this pod template running", and roll out changes to the template gradually.
  • Service: a stable name and virtual IP that load-balances across the matching pods (http://library-service).
  • Ingress (or the newer Gateway API): routes external HTTP(S) traffic to Services by host and path.
  • ConfigMap and Secret: configuration and sensitive values, injected as environment variables or files.
  • HorizontalPodAutoscaler: adds or removes replicas based on CPU or custom metrics.

A Deployment for the library service, with the probes and resources discussed in the previous lessons:

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: library-service
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1            # at most 1 extra pod during the rollout
      maxUnavailable: 0      # never drop below 3 ready pods
  selector:
    matchLabels:
      app: library-service
  template:
    metadata:
      labels:
        app: library-service
    spec:
      terminationGracePeriodSeconds: 45
      containers:
        - name: app
          image: ghcr.io/acme/library-service:1.4.2
          ports:
            - containerPort: 8080
          envFrom:
            - configMapRef:
                name: library-config
          env:
            - name: SPRING_PROFILES_ACTIVE
              value: prod
            - name: SPRING_DATASOURCE_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: library-db
                  key: password
            - name: JAVA_TOOL_OPTIONS
              value: "-XX:MaxRAMPercentage=75"
          resources:
            requests:
              cpu: "500m"
              memory: "768Mi"
            limits:
              memory: "768Mi"
          startupProbe:
            httpGet: { path: /actuator/health/liveness, port: 8080 }
            periodSeconds: 2
            failureThreshold: 60       # allow up to 2 minutes to start
          livenessProbe:
            httpGet: { path: /actuator/health/liveness, port: 8080 }
            periodSeconds: 10
          readinessProbe:
            httpGet: { path: /actuator/health/readiness, port: 8080 }
            periodSeconds: 5
          lifecycle:
            preStop:
              exec:
                command: ["sleep", "5"]  # let the load balancer stop sending traffic first
---
apiVersion: v1
kind: Service
metadata:
  name: library-service
spec:
  selector:
    app: library-service
  ports:
    - port: 80
      targetPort: 8080
Terminal
kubectl apply -f k8s/                                 # create or update everything in the folder
kubectl rollout status deployment/library-service      # watch the rollout
kubectl get pods -l app=library-service
kubectl logs -f deployment/library-service
kubectl rollout undo deployment/library-service        # back to the previous version

The startup probe protects slow-starting JVMs: liveness checks only begin after it succeeds, so Kubernetes doesn't kill a pod that is still warming up. The readiness probe decides when a pod receives traffic, which is what makes rolling updates safe. The simulation below plays out a rolling update with maxSurge: 1 and maxUnavailable: 0, first with a good version and then with a broken one whose readiness never succeeds:

Java Simulating a Kubernetes rolling update

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.

During the good rollout, ready capacity never dropped below three pods. The broken v3 never became ready, so no v2 pod was ever terminated: users kept being served by the old version while the team rolled back. That safety net only works if your readiness check is honest, which is why the health lessons insisted on correct probes.

Deployment strategies

  • Rolling update: replace pods gradually (shown above). The default; old and new versions run side by side briefly.
  • Blue-green: run the new version (green) next to the old (blue), test it, then switch all traffic at once; switching back is instant.
  • Canary: send a small percentage of traffic (say 5%) to the new version, watch error rates and latency, then increase step by step. Tools like Argo Rollouts or Flagger automate this based on metrics.
  • Feature flags: deploy code switched off and enable it separately, per user group. Deploying and releasing become independent decisions.

GraalVM native images

A normal Java service starts a JVM, loads and verifies classes, and warms up with the JIT compiler. Startup takes seconds and memory use is substantial, but peak performance is excellent. GraalVM Native Image compiles the application ahead of time into a standalone executable:

  • Startup in tens of milliseconds and much lower memory, great for scale-to-zero, serverless functions and CLIs.
  • Closed-world assumption: everything reachable must be known at build time. Reflection, dynamic proxies, resources and serialization need metadata. Spring Boot's AOT processing generates most of it, and many libraries ship their own.
  • Slow builds (minutes, several GB of RAM) and some libraries that don't work or need extra configuration.
  • Peak throughput is usually somewhat lower than a warmed-up JIT unless you use profile-guided optimization (available in Oracle GraalVM).

With Spring Boot, building a native image takes the GraalVM native build tools plugin and one of:

Terminal
./mvnw -Pnative native:compile          # native executable, needs GraalVM installed locally
./mvnw -Pnative spring-boot:build-image # a container image with the native executable, via buildpacks

Test the native build in CI, not only on the JVM: code that works on the JVM can fail at runtime in a native image if reflection metadata is missing.

There is also a middle road. The OpenJDK Project Leyden work brought an AOT cache in Java 24 and 25: you do a training run with -XX:AOTCacheOutput=app.aot, then start with -XX:AOTCache=app.aot, and the JVM reuses classes already loaded and linked (and, since Java 25, method profiles), cutting startup substantially while keeping the normal JVM and its full compatibility. Spring Boot's CDS support works in the same spirit.

A CI/CD pipeline

Continuous integration builds and tests every change. Continuous delivery keeps every successful build deployable; continuous deployment goes further and deploys it automatically. A typical pipeline for a Java service:

  1. Build and test: ./mvnw verify runs unit and integration tests (with Testcontainers), static analysis and coverage (Code Quality and Static Analysis).
  2. Package: build the container image once, tagged with the Git commit SHA.
  3. Scan: check dependencies and the image for known vulnerabilities.
  4. Push the image to the registry.
  5. Deploy to staging automatically and run smoke tests against it.
  6. Promote the same image to production, after an approval or automatically, using a rolling or canary strategy.
  7. Verify: watch error rate and latency dashboards; roll back automatically if they degrade.

The key idea in steps 2 and 6: build once, deploy the same artifact everywhere. Never rebuild for production; what you tested is exactly what you ship. Here is the start of such a pipeline with GitHub Actions:

YAML
# .github/workflows/ci.yml
name: ci
on:
  push:
    branches: [main]
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: "25"
          cache: maven
      - name: Build and test
        run: ./mvnw -B verify
      - name: Build and push image
        if: github.ref == 'refs/heads/main'
        run: |
          IMAGE=ghcr.io/acme/library-service:${{ github.sha }}
          echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin
          docker build -t "$IMAGE" .
          docker push "$IMAGE"

Deployment to Kubernetes then often uses GitOps: the pipeline updates the image tag in a Git repository of manifests, and a tool like Argo CD or Flux applies the change to the cluster. Every production change is a reviewed, revertible commit.

A production checklist

  • Configuration and secrets come from the environment; the artifact is identical everywhere.
  • Health endpoints with correct liveness, readiness and startup probes.
  • Graceful shutdown that fits inside the platform's grace period.
  • Memory and CPU limits set, with MaxRAMPercentage tuned.
  • Structured logs to stdout, metrics, traces and alerts in place.
  • Backward-compatible database migrations, run before or during startup.
  • At least two replicas, and a tested rollback.
  • Automated pipeline: build once, test, scan, deploy the same image.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. The same image runs in staging and production. In production, SPRING_DATASOURCE_URL is set as an environment variable and application-prod.yml also sets spring.datasource.url. Which value does Spring Boot use?

    Environment variables override properties from files, both profile-specific and default ones. Command-line arguments would win over both.
  2. 2. Migration V2 has already run in production. A developer notices a mistake in it. What should they do?

    Applied migrations are immutable; the runner detects edits by checksum. Fixes go into a new versioned migration.
  3. 3. A Deployment uses maxSurge 1 and maxUnavailable 0. The new version's readiness probe never succeeds. What happens to the old pods?

    With maxUnavailable 0, an old pod is only removed after a new pod becomes ready. A broken version stalls the rollout instead of causing an outage.
  4. 4. Which is the strongest reason to choose a GraalVM native image for a service?

    Native images start in milliseconds with a small footprint, but build slowly, need reachability metadata, and usually don't beat a warmed-up JIT in peak throughput.
  5. 5. Why should a pipeline build the image once and promote the same image from staging to production?

    Build once, deploy everywhere guarantees the tested artifact is the shipped one. Differences come only from configuration.

Summary

  • Deployable artifacts: executable JARs (manifest Main-Class, Spring Boot's launcher), WARs for legacy servers, container images (the modern default) and native executables.
  • On a VM, run the JAR with systemd; elsewhere, ship an image to a PaaS, serverless containers or Kubernetes. Prefer a managed database.
  • Configuration comes from the environment with clear precedence (command line > system properties > env vars > profile files > defaults); secrets come from a secret store at runtime.
  • Use Flyway or Liquibase with immutable, versioned migrations, and expand/contract for breaking schema changes during rolling deployments.
  • Kubernetes basics: Deployment, Pod, Service, Ingress, ConfigMap, Secret; set resources and startup, liveness and readiness probes. Rolling updates with maxUnavailable: 0 stop a bad version from taking over; blue-green, canary and feature flags reduce risk further.
  • GraalVM native images give millisecond startup at the cost of build time and closed-world constraints; the JDK's AOT cache improves JVM startup without those constraints.
  • CI/CD: build and test every change, build the image once, scan, push, deploy to staging, promote the same image, and watch the metrics.

Next: Service Discovery with Eureka.