Deployment: Shipping Your Spring Boot App

8 min read

Building a Spring Boot application is only half the battle. The other half is getting it out of your local development environment and into the hands of users. In modern software engineering, deployment is no longer about dragging and dropping files onto a remote server via FTP. It is about packaging, configuring, and containerizing your application so it can run reliably anywhere—from a laptop to a massive Kubernetes cluster in the cloud.

Let's break down the industry standards for shipping Spring Boot applications.


1. Packaging for Production: The Executable Fat JAR Explained 📦

Definition

An executable Fat JAR (Java ARchive), sometimes called an Uber-JAR, is a single, compressed file that contains your compiled application code, all required third-party dependencies, and an embedded web server (like Tomcat, Jetty, or Undertow).

The Problem

Historically, deploying Java web applications was a heavy, multi-step chore. You had to package your code as a WAR (Web Application Archive) file and deploy it into a standalone, pre-installed web server (like Apache Tomcat or IBM WebSphere). If the server on the production machine was a different version than the one on your local machine, or if it was misconfigured, the application would crash during deployment.

The Solution

The Fat JAR flips the script. Instead of deploying your application into a server, you deploy the server inside your application. As long as the target machine has a Java Virtual Machine (JVM) installed, your application will run exactly as it did on your local machine.

Imagine buying a piece of furniture. In the old days, you just bought the raw wood (the WAR file) and had to take it to a specific carpenter's workshop (the external server) that had the exact tools to build it. A Fat JAR is like modern IKEA furniture: it comes in a single box with the exact Allen wrench and screws you need included. You can build it anywhere.

Under the Hood

Java, by default, does not know how to load a .jar file nested inside another .jar file. Spring Boot solves this by injecting a custom class loader (spring-boot-loader) into the archive. When you run the JAR, the JVM actually triggers Spring's JarLauncher, which knows how to dynamically read the nested third-party libraries located in the BOOT-INF/lib directory.

Industry Practice

Generating a Fat JAR is handled entirely by your build tool (Maven or Gradle) via the Spring Boot plugin.

To package your application, run:

bash
# For Maven
./mvnw clean package

# For Gradle
./gradlew bootJar

To run the packaged application:

bash
java -jar target/myapp-0.0.1-SNAPSHOT.jar

Fun Fact: The term "Uber-JAR" comes from the German word "über", meaning "over" or "above"—signifying an all-encompassing archive.


2. Environment Configurations: Using Spring Profiles (dev, test, prod) ⚙️

Definition

Spring Profiles are a core framework feature that allows you to group application settings, credentials, and beans, and activate them selectively based on the environment the application is running in.

The Problem

Your application acts differently depending on where it lives. On your local machine, it connects to a local database at localhost:5432. In production, it connects to a highly secure cloud database. Hardcoding these URLs or manually editing a configuration file before every deployment is dangerous, error-prone, and scales poorly.

The Solution

Profiles allow you to define distinct configuration files for each environment. You create specialized files like application-dev.yml and application-prod.yml. Spring Boot loads the correct configurations dynamically when you tell it which profile is "active."

Imagine a modern smartphone. When you are at work, you put it in "Do Not Disturb" mode (a profile), which silences notifications. When you are at home, you switch it to "Personal" mode, turning on ringtones and media volume. The physical phone (your code) never changes, but its behavior adapts to its environment based on the active mode.

Industry Practice

The standard industry practice is the Base + Profile Pattern.

  1. application.yml: Contains base configurations true for every environment (e.g., application name, default port).
  2. application-{profile}.yml: Contains environment-specific overrides (e.g., database URLs).
yaml
# application.yml (Base)
spring:
  application:
    name: payment-service
server:
  port: 8080
yaml
# application-dev.yml (Developer Machine)
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/dev_db

Activating a Profile
You can activate a profile via command-line arguments when running your JAR:

bash
java -jar target/payment-service.jar --spring.profiles.active=dev

⚠️ Crucial Security Standard:
Never store production passwords or API keys in application-prod.yml if that file is committed to Git. Spring Boot has a strict hierarchy where Environment Variables always win. In production, you define the variables directly on the server or container:

bash
export SPRING_DATASOURCE_PASSWORD=super_secret_password
java -jar target/payment-service.jar --spring.profiles.active=prod

3. Containerizing Spring Boot: Writing Your First Dockerfile 🐳

Definition

Containerization involves wrapping the Fat JAR, the Java Runtime Environment (JRE), and OS-level dependencies into an isolated, executable package called a Docker Image. A Dockerfile is a text-based blueprint that defines exactly how to assemble this image.

The Problem

The Fat JAR solved the "I need a Tomcat server" problem, but you still need the correct version of Java installed on the host machine. If your production server has Java 11 installed, but your application was compiled for Java 21, it will crash. The infamous developer excuse, "It works on my machine," stems from these underlying system differences.

The Solution

Docker solves this by putting both the application and the exact Java environment it needs inside a standardized container. You no longer just ship the code; you ship the environment.

Imagine you have an exotic fish (your application) that needs saltwater at exactly 24°C (Java 21). You cannot just throw it into a random freshwater lake (the production server) and hope it survives. Containerization is like putting the fish inside a sealed, climate-controlled aquarium and dropping the entire aquarium into the lake.

Industry Practice

In most modern CI/CD pipelines (like GitHub Actions), the JAR file is built before Docker is invoked. Therefore, your Dockerfile only needs to take the pre-built JAR and place it inside a lightweight Java Runtime image (like Eclipse Temurin).

Your First Production-Ready Dockerfile:

dockerfile
# Use a lightweight official JRE base image (Alpine Linux is very small)
FROM eclipse-temurin:21-jre-alpine

# Set a working directory inside the container
WORKDIR /app

# Copy the pre-built Fat JAR from your host machine into the container
COPY target/*.jar app.jar

# Document the port the container listens on
EXPOSE 8080

# Define the command that runs when the container starts
ENTRYPOINT ["java", "-jar", "app.jar"]

To build and run this container:

bash
docker build -t my-spring-app .
docker run -p 8080:8080 my-spring-app

4. Optimizing Docker Images: Buildpacks and Layered JARs 🏗️

Definition

  • Layered JARs: A structure that physically divides the Spring Boot Fat JAR into distinct layers based on how frequently they change (e.g., separating third-party dependencies from your actual application code).
  • Cloud Native Buildpacks (CNB): A technology that inspects your source code and automatically generates a highly optimized, production-ready container image without requiring you to write or maintain a Dockerfile.

The Problem

A typical Spring Boot Fat JAR is quite large—often 50MB to 150MB. Most of that weight comes from third-party dependencies (like Spring Web, Hibernate, and Jackson) which rarely change. Your actual custom application code might only be 200KB.

In a standard Docker setup (like the Dockerfile above), every time you fix a single typo in your code and rebuild the image, Docker copies the entire 150MB JAR as a single new layer. This creates bloated images, eats up registry storage, and makes deployments dreadfully slow over the network.

The Solution

Layered JARs separate the rarely changing dependencies from your frequently changing code. Docker caches the heavy dependencies layer, meaning subsequent builds only need to upload the 200KB code change. Buildpacks take this a step further by automating the entire process out-of-the-box.

Imagine packing a suitcase for a long trip. If you pack your dirty socks (frequently changed code) in the exact same compartment as your heavy hiking boots (rarely changed dependencies), you have to unpack the whole suitcase every time you change your socks. Layering puts the boots in a bottom compartment and the socks at the very top. You only open the top flap when you need to swap socks.

Industry Practice

Approach 1: Using Buildpacks (The Modern Standard)
You don't even need a Dockerfile. Spring Boot (v2.3+) includes built-in support for Cloud Native Buildpacks via the Paketo buildpacks. It automatically layers your application and uses optimized memory settings.

Run this command, and Spring Boot will talk directly to your Docker daemon to produce an optimized image:

bash
# For Maven
./mvnw spring-boot:build-image

# For Gradle
./gradlew bootBuildImage

Approach 2: Manual Layer Extraction via Dockerfile
If your organization requires explicit Dockerfiles (for compliance or custom OS tooling), you can extract the layers manually. Spring Boot 3 enables layering by default.

dockerfile
# Stage 1: Extract layers
FROM eclipse-temurin:21-jre-alpine AS builder
WORKDIR /builder
COPY target/*.jar application.jar
# The layertools jarmode extracts the jar into separate folders
RUN java -Djarmode=layertools -jar application.jar extract

# Stage 2: Build optimized image
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
# Copy the extracted layers in order from least frequently changed to most
COPY --from=builder /builder/dependencies/ ./
COPY --from=builder /builder/spring-boot-loader/ ./
COPY --from=builder /builder/snapshot-dependencies/ ./
COPY --from=builder /builder/application/ ./

# Run via the custom launcher instead of a Fat JAR
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]

Because the application code is copied last, Docker caches everything above it. Your build times and upload speeds will drop dramatically!


References & Extra Reading 📚

Challenge

You are responsible for preparing a Spring Boot application for production. Your task is to create the necessary configuration and containerization files.

The application has been packaged into an executable Fat JAR named app.jar.

Your goal is to write three distinct configuration blocks: a Dockerfile, a base application.yml, and a production-specific application-prod.yml.

Requirements:

  1. Dockerfile:

    • Use eclipse-temurin:21-jre-alpine as the base image.
    • Copy the app.jar from the build context into the image's root directory.
    • Expose the standard HTTP port 8080.
    • Set the startup command to execute the JAR file, ensuring the prod Spring profile is active.
  2. Base Configuration (application.yml):

    • Set the application name to my-production-app.
    • Configure the default server port to 8080.
    • Define a default datasource configuration for an in-memory H2 database with the URL jdbc:h2:mem:testdb.
  3. Production Profile Configuration (application-prod.yml):

    • Override the server port to 80.
    • Configure the datasource for a PostgreSQL database.
    • The database URL, username, and password must be dynamically configured from the following environment variables, respectively: PROD_DB_URL, PROD_DB_USERNAME, and PROD_DB_PASSWORD.

Expected result

The submission must contain three distinct blocks of code, one for each required file (Dockerfile, application.yml, application-prod.yml).

  1. Dockerfile:

    • Must use the FROM eclipse-temurin:21-jre-alpine instruction.
    • Must include a COPY instruction, such as COPY app.jar /app.jar.
    • Must correctly EXPOSE 8080.
    • Must define the entry point or command to run the application with the prod profile activated. A correct implementation would be ENTRYPOINT ["java", "-jar", "/app.jar", "--spring.profiles.active=prod"] or a similar valid alternative using CMD.
  2. application.yml:

    • Must be valid YAML.
    • Must define spring.application.name: my-production-app.
    • Must define server.port: 8080.
    • Must define spring.datasource.url: jdbc:h2:mem:testdb.
  3. application-prod.yml:

    • Must be valid YAML.
    • Must override the port with server.port: 80.
    • Must configure the datasource using placeholders for environment variables. The correct syntax is ${VARIABLE_NAME}.
      • spring.datasource.url must be set to ${PROD_DB_URL}.
      • spring.datasource.username must be set to ${PROD_DB_USERNAME}.
      • spring.datasource.password must be set to ${PROD_DB_PASSWORD}.
yaml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.