Part 5 · Chapter 17

Java Services Deployment

From JAR to JVM in production — Spring Boot, the JVM tuning levers, and running Java reliably at scale.

What you'll learn in this chapter

  • How Java apps are packaged (JAR, WAR, fat JAR)
  • Running a Spring Boot app and tuning the JVM for production
  • Managing Java services with systemd
  • Spring Boot profiles and environment-specific configuration
  • Dockerizing Java with multi-stage builds
  • Spring Boot Actuator for health checks and metrics
  • Quarkus and Micronaut as lightweight alternatives

The Universal Translator

Java invented the phrase "Write Once, Run Anywhere." The Java Virtual Machine (JVM) is like a universal translator: you compile Java code into bytecode, and the JVM translates that bytecode into native machine code on whatever operating system is running — Windows, Linux, macOS. The JVM handles the translation, so your compiled artifact works everywhere.

That's why Java has remained the dominant language in enterprise software for almost 30 years. Millions of production systems run on the JVM — banks, telecoms, airlines, e-commerce platforms. If you're doing DevOps, you will encounter Java services.

☕ The Container Ship Analogy

A Java JAR file is like a shipping container. Everything the app needs is sealed inside — compiled code, libraries, resources. The JVM is the port infrastructure that can receive and unload that container on any dock (operating system) in the world. You ship one container; it works at every port.

Packaging: JAR, WAR, and the Fat JAR

Java services are typically packaged as one of three formats:

  • JAR (Java ARchive): a ZIP of compiled .class files. The classic format.
  • WAR (Web ARchive): meant for deployment into a separate app server like Tomcat or WildFly. The old way.
  • Fat JAR (executable JAR): a self-contained JAR that bundles the app and all dependencies and an embedded web server (Tomcat or Undertow). This is what Spring Boot produces. You run it directly: java -jar myapp.jar.
📦 Key Term: Fat JAR

A fat JAR (also called an uber-JAR or executable JAR) packages your compiled code, all Maven/Gradle dependencies, and an embedded web server into a single file. You need nothing else installed beyond the JRE to run it.

Building with Maven and Gradle

Spring Boot projects use either Maven (pom.xml) or Gradle (build.gradle) as their build tool.

# Maven: build and package
mvn clean package

# Skip tests during build (use only if you've already run them)
mvn clean package -DskipTests

# Gradle: build the runnable JAR
./gradlew bootJar

# The output is in target/ (Maven) or build/libs/ (Gradle)
ls target/*.jar
# myapp-1.0.0.jar

# Run it
java -jar target/myapp-1.0.0.jar

JVM Tuning for Production

The JVM is highly configurable. Its defaults are rarely optimal for production. Running Java on a server without tuning is like driving a race car with the handbrake on.

The Essential JVM Flags

java \
  -Xms512m \              # initial heap size (allocate upfront)
  -Xmx1024m \             # max heap size (never exceed this)
  -XX:+UseG1GC \           # G1 garbage collector — good default since Java 9
  -XX:MaxGCPauseMillis=200 \  # target GC pause below 200ms
  -XX:+HeapDumpOnOutOfMemoryError \  # save heap dump on OOM
  -XX:HeapDumpPath=/var/log/myapp/ \
  -Dspring.profiles.active=production \
  -jar myapp.jar
💡 Heap Size Rule of Thumb

Set -Xmx to roughly 70–75% of available RAM, leaving headroom for the OS, off-heap memory, and other processes. On a 2 GB server: -Xms256m -Xmx1400m. On a 4 GB server: -Xms512m -Xmx2800m.

Running as a systemd Service

On a Linux server, the right way to run a long-lived process is as a systemd service. It starts on boot, restarts on crash, and logs go to the journal.

# /etc/systemd/system/myapp.service
[Unit]
Description=My Spring Boot Application
After=network.target

[Service]
User=myapp
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/java \
  -Xms512m \
  -Xmx1024m \
  -XX:+UseG1GC \
  -Dspring.profiles.active=production \
  -jar /opt/myapp/myapp.jar
EnvironmentFile=/etc/myapp/app.env
SuccessExitStatus=143   # Spring Boot exits with 143 on SIGTERM
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
# Enable and start
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp

# Check status
sudo systemctl status myapp

# Follow logs in real time
sudo journalctl -u myapp -f

# See last 100 lines
sudo journalctl -u myapp -n 100

Spring Boot Profiles — Environment Configuration

Spring Boot profiles let you have different configuration for development, staging, and production without changing code.

# src/main/resources/application.yml — base config
spring:
  application:
    name: my-api
server:
  port: 8080

---
# src/main/resources/application-production.yml
spring:
  config:
    activate:
      on-profile: production
  datasource:
    url: ${DATABASE_URL}
    username: ${DB_USER}
    password: ${DB_PASSWORD}
  jpa:
    hibernate:
      ddl-auto: validate   # NEVER use 'create' or 'update' in production
logging:
  level:
    root: WARN
    com.myapp: INFO
management:
  endpoints:
    web:
      exposure:
        include: health,metrics,prometheus

Activate a profile by setting an environment variable:

# In /etc/myapp/app.env
SPRING_PROFILES_ACTIVE=production
DATABASE_URL=jdbc:postgresql://localhost:5432/mydb
DB_USER=myapp
DB_PASSWORD=supersecret

Dockerfile for Spring Boot

A multi-stage build gives you a small production image — the final image contains only the JRE (runtime) not the full JDK (compiler), significantly reducing image size.

# Stage 1: Build with Maven
FROM eclipse-temurin:21-jdk-alpine AS builder
WORKDIR /app

# Download dependencies first (cached layer)
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw dependency:go-offline

# Build the JAR
COPY src src
RUN ./mvnw clean package -DskipTests

# Stage 2: Run with JRE only (smaller image)
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app

COPY --from=builder /app/target/*.jar app.jar

EXPOSE 8080

ENTRYPOINT ["java", \
  "-Xms256m", \
  "-Xmx512m", \
  "-XX:+UseG1GC", \
  "-jar", "/app/app.jar"]

Spring Boot Actuator — Health & Metrics

Spring Boot Actuator exposes a /actuator/health endpoint that Kubernetes, load balancers, and monitoring tools use to check if your app is alive and ready.

# application.yml — enable actuator endpoints
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus
  endpoint:
    health:
      show-details: always

Hit GET /actuator/health and you get:

{
  "status": "UP",
  "components": {
    "db": { "status": "UP", "details": { "database": "PostgreSQL" } },
    "diskSpace": { "status": "UP", "details": { "free": 42567892992 } }
  }
}

GitHub Actions CI/CD for Spring Boot

name: Build and Deploy Java Service

on:
  push:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up JDK 21
        uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'
          cache: maven

      - name: Run tests
        run: mvn test

      - name: Build JAR
        run: mvn package -DskipTests

      - name: Build Docker image
        run: docker build -t myapp:${{ github.sha }} .

      - name: Push to registry
        run: |
          docker push myregistry/myapp:${{ github.sha }}

Quarkus and Micronaut — Lighter Java

Spring Boot's startup time can be 3–10 seconds, which is a problem for serverless functions or fast-scaling Kubernetes pods. Two frameworks solve this:

  • Quarkus (Red Hat): "Supersonic Subatomic Java." Compiles to a native binary using GraalVM — starts in milliseconds, uses 10x less memory. Build with ./mvnw package -Pnative.
  • Micronaut: ahead-of-time compilation, tiny memory footprint, built-in cloud-native features. Starts in under 1 second.

For most Java microservices in 2026, Spring Boot remains the default. Use Quarkus or Micronaut when startup time and memory are genuine constraints (serverless, massive scale).

Chapter Summary

  • Spring Boot produces self-contained executable fat JARs — run with java -jar
  • Tune the JVM with -Xms, -Xmx, and -XX:+UseG1GC for production
  • Run Java as a systemd service for auto-start and auto-restart
  • Use Spring Boot profiles and EnvironmentFile to keep secrets out of code
  • Multi-stage Docker builds (JDK build → JRE run) produce small, fast images
  • Spring Boot Actuator gives you /actuator/health and /actuator/prometheus for free
  • Quarkus and Micronaut are the go-to alternatives when startup time and memory are critical