Learn Spring Β· 15/15

Deployment and Containerization

16 min read

1. Packaging Spring Boot Applications: Executable JARs Explained πŸ“¦

Alright, let's get this deployment party started! You've built a fantastic Spring Boot application. It runs beautifully on your local machine. But how do you get it from your cozy development environment to the wild world of servers where users can actually interact with it? The answer, my friend, lies in packaging.

The Problem: "It works on my machine!" πŸ€”

This is probably the most infamous phrase in software development. You write your code, test it, and everything is perfect. Then you hand it over to someone else, or try to run it on a different computer, and... it breaks. Why? Maybe they don't have the right version of Java installed. Maybe they're missing a crucial library your application depends on. It's like trying to bake a cake and giving someone a list of ingredients without the recipe or the oven.

The Solution: The Executable JAR JAR-velous! ✨

A JAR (Java ARchive) file is like a zip file for Java code. It bundles up all your compiled code (.class files) and any other resources your application needs (like configuration files, images, etc.) into a single, neat package.

But a Spring Boot Executable JAR is something even more special. It's a self-contained, runnable unit. Think of it as a magical box that contains not only your application's code but also everything it needs to run, including an embedded web server (like Tomcat, by default). This means you don't need to have a separate web server installed on the machine where you want to run your application.

How does it solve the problem?

By bundling everything together, the executable JAR ensures that your application runs consistently across different environments. As long as the machine has a Java Runtime Environment (JRE) installed, you can run your entire application with a single, simple command. No more "it works on my machine" drama!

Under the Hood: What's Inside this Magic Box? πŸ§™β€β™‚οΈ

If you were to peek inside a Spring Boot executable JAR, you'd find a specific structure. The Spring Boot build plugins (for Maven or Gradle) are responsible for creating this structure. A key part is the BOOT-INF directory.

  • BOOT-INF/classes/: This is where your application's own compiled code lives.
  • BOOT-INF/lib/: This directory contains all the third-party libraries (dependencies) your application needs.
  • org/springframework/boot/loader/: This contains the special code that knows how to start your application and the embedded server.

When you run the JAR, this loader code kicks in first, sets everything up, and then hands over control to your application's main method. It's like a well-organized event crew setting up the stage, sound, and lights before the main act comes on.

How to Create an Executable JAR πŸ› οΈ

The good news is that if you used Spring Initializr to create your project, the necessary configuration is already there!

With Maven:

The spring-boot-maven-plugin is your best friend here. It's included in your pom.xml by default.

xml
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

To build the executable JAR, you simply run the following command in your project's root directory:

bash
mvn clean package

This will compile your code, run any tests, and then package everything into a JAR file in the target directory. The file will typically be named something like your-app-name-0.0.1-SNAPSHOT.jar.

With Gradle:

Similarly, for Gradle, the org.springframework.boot plugin in your build.gradle file takes care of everything.

groovy
plugins {
	id 'org.springframework.boot' version '3.2.2' // Use the appropriate version
	id 'io.spring.dependency-management' version '1.1.4'
	id 'java'
}

To build the executable JAR with Gradle, run:

bash
./gradlew build

This will create the JAR file in the build/libs directory.

Running Your Executable JAR πŸš€

Once you have your shiny new JAR file, running it is incredibly simple. Just open your terminal, navigate to the directory where the JAR is located, and run:

bash
java -jar your-app-name-0.0.1-SNAPSHOT.jar

And that's it! Your Spring Boot application will start up, and you'll see the familiar log output in your console.

Fun Fact! πŸŽ‰

Did you know that the "fat JAR" (another name for the executable JAR) concept wasn't entirely new, but Spring Boot popularized it to a massive extent? It simplified Java web development so much that many developers who had previously found it cumbersome suddenly found it enjoyable. It was a real game-changer!


2. Containerizing Your App: Writing an Optimized Dockerfile for Spring Boot 🐳

Now that you have a portable, executable JAR, you might be thinking, "Great, but what if the server doesn't have the correct version of Java installed?" or "What if my application needs other services, like a database?" This is where containerization comes to the rescue!

The Problem: Environmental Inconsistencies πŸŒͺ️

Even with an executable JAR, you're still dependent on the underlying operating system and its installed software (like the JRE). Different environments (development, testing, production) might have slight differences that can lead to unexpected behavior. It's like trying to run a highly specific science experiment in a lab where the temperature and humidity keep changing.

The Solution: Docker Containers πŸ“¦

Docker allows you to package your application, along with all its dependencies, into a standardized unit called a container. A container is a lightweight, standalone, executable package that includes everything needed to run a piece of software, including the code, a runtime, system tools, system libraries, and settings.

Think of it like a shipping container. It doesn't matter what's inside – electronics, clothes, or even a car – the container itself has a standard size and shape, making it easy to transport and handle. Similarly, a Docker container can run on any machine that has Docker installed, regardless of the underlying operating system.

The Dockerfile: Your Container's Blueprint πŸ“œ

A Dockerfile is a text file that contains a set of instructions on how to build a Docker image. An image is a template for creating containers.

Here's a simple, yet optimized, Dockerfile for a Spring Boot application:

dockerfile
# Start with a base image containing Java runtime
FROM openjdk:17-jdk-slim

# Add a volume pointing to /tmp
VOLUME /tmp

# Make port 8080 available to the world outside this container
EXPOSE 8080

# The application's JAR file
ARG JAR_FILE=target/*.jar

# Add the application's JAR to the container
ADD ${JAR_FILE} app.jar

# Run the JAR file
ENTRYPOINT ["java","-jar","/app.jar"]

Let's break this down:

  • FROM openjdk:17-jdk-slim: This tells Docker to use an official OpenJDK image with Java 17 as the base for our image. The slim variant is a smaller, more secure version.
  • VOLUME /tmp: This creates a mount point for a temporary volume. Spring Boot applications sometimes use this for temporary files.
  • EXPOSE 8080: This informs Docker that the container will listen on port 8080 at runtime. It's good practice for documentation.
  • ARG JAR_FILE=target/*.jar: This defines a variable JAR_FILE that points to our executable JAR in the target directory.
  • ADD ${JAR_FILE} app.jar: This copies our application's JAR file from the host machine into the container's filesystem and renames it to app.jar.
  • ENTRYPOINT ["java","-jar","/app.jar"]: This is the command that will be executed when the container starts. It's the same command we used to run the JAR file manually.

Building and Running Your Docker Image πŸ—οΈ

  1. Build the Image: Make sure you are in the root directory of your project where the Dockerfile is located. Then run:

    bash
    docker build -t your-app-name .
    • docker build: The command to build a Docker image.
    • -t your-app-name: This "tags" the image with a name so you can easily refer to it later.
    • .: This tells Docker to look for the Dockerfile in the current directory.
  2. Run the Container: Once the image is built, you can run a container from it:

    bash
    docker run -p 8080:8080 your-app-name
    • docker run: The command to run a container.
    • -p 8080:8080: This "publishes" the container's port 8080 to the host machine's port 8080. This is what allows you to access your application from your browser at http://localhost:8080.
    • your-app-name: The name of the image to run.

A More Optimized Dockerfile (Multi-stage build) πŸš€

The previous Dockerfile is good, but we can do better! A multi-stage build allows us to use one image for building our application (which might contain build tools like Maven or Gradle) and a separate, smaller image for running it. This results in a smaller, more secure production image.

dockerfile
# Stage 1: Build the application
FROM maven:3.8.4-openjdk-17 AS build
WORKDIR /app
COPY . .
RUN mvn clean package -DskipTests

# Stage 2: Create the final, smaller image
FROM openjdk:17-jdk-slim
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

What's happening here?

  • Stage 1 (aliased as build):
    • We start with a Maven image that has Java and Maven pre-installed.
    • We copy our project files into the image.
    • We run mvn clean package to build our executable JAR.
  • Stage 2:
    • We start with a fresh, slim OpenJDK image.
    • COPY --from=build ...: This is the magic part! We copy the JAR file created in the build stage into our new, clean image.
    • The rest is the same as before.

This approach keeps our final image lean and mean, without all the build dependencies.

Industry Practice: Why does this matter? πŸ€“

In a real-world scenario, you'll be building and deploying your application many times. Smaller Docker images mean faster build times, less storage space on your servers, and faster startup times for your containers. This all adds up to a more efficient and cost-effective development and deployment process. It's like packing only the essentials for a trip instead of your entire wardrobe!


3. Running Local Environments: Orchestrating App + DB with Docker Compose 🎢

Your application is now neatly packaged in a Docker container. But what if your application needs to talk to a database? Or a message queue? Or any other external service? You could run each of them in a separate Docker container, but managing them all individually would be a pain.

The Problem: Juggling Multiple Containers 🀹

Imagine you're a conductor of an orchestra. You have the violins, the cellos, the trumpets, and the drums. You need to make sure they all start at the same time, are in tune with each other, and can communicate effectively. Trying to give individual instructions to each musician would be chaotic.

This is similar to managing multiple Docker containers for your application's environment. You need a way to define, configure, and run them all together as a single unit.

The Solution: Docker Compose 🎼

Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application's services. Then, with a single command, you can create and start all the services from your configuration.

It's like having a musical score for your entire orchestra. The score tells each musician what to play and when, and you, the conductor, just have to give the signal to start.

The docker-compose.yml File: Your Composition πŸ“

Let's say our Spring Boot application needs a PostgreSQL database. Here’s what a docker-compose.yml file for this setup would look like:

yaml
version: '3.8'

services:
  app:
    build: .
    ports:
      - "8080:8080"
    depends_on:
      - db
    environment:
      - SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/mydatabase
      - SPRING_DATASOURCE_USERNAME=myuser
      - SPRING_DATASOURCE_PASSWORD=mypassword

  db:
    image: postgres:14.1
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_DB=mydatabase
      - POSTGRES_USER=myuser
      - POSTGRES_PASSWORD=mypassword

Let's dissect this composition:

  • version: '3.8': Specifies the version of the Docker Compose file format.
  • services:: This is where we define our different containers (services).
  • app service:
    • build: .: This tells Docker Compose to build the image for this service using the Dockerfile in the current directory.
    • ports: - "8080:8080": Maps port 8080 of the container to port 8080 on the host machine.
    • depends_on: - db: This is crucial! It tells Docker Compose to start the db service before starting the app service. Your app needs the database to be ready before it can connect.
    • environment:: Here, we set environment variables that our Spring Boot application will use to connect to the database. Notice how the database URL points to db:5432. db is the service name of our PostgreSQL container, and Docker Compose provides automatic service discovery, so containers can talk to each other using their service names.
  • db service:
    • image: postgres:14.1: We use a pre-built PostgreSQL image from Docker Hub.
    • ports: - "5432:5432": Maps the PostgreSQL port so you can potentially connect to it from your host machine for debugging.
    • environment:: These environment variables are used to configure the PostgreSQL container itself, like creating the initial database, user, and password.

Running Your Orchestra 🎻

With your docker-compose.yml file in place, starting your entire local development environment is as simple as running:

bash
docker-compose up

This command will:

  1. Build the image for your app service (if it doesn't exist).
  2. Pull the postgres image for your db service.
  3. Create and start the containers for both services in the correct order.
  4. Attach your terminal to the logs of all the containers, so you can see what's happening.

To stop everything and remove the containers, you can use:

bash
docker-compose down

Real-world Simulation πŸ™οΈ

Imagine building a model of a city. Your application is the main skyscraper. The database is the power plant. A messaging service could be the communication tower. Docker Compose is the master plan for the city. It defines where each building goes, how they are connected by roads and power lines, and the order in which they should be built. With the master plan, you can construct and demolish your model city with simple commands.


4. CI/CD Basics: Automating the Build and Test Pipeline (GitHub Actions overview) πŸ€–

So far, we've learned how to package, containerize, and run our application locally. This is great for development, but in a real project, you need a way to automate the process of building, testing, and deploying your code every time you make a change. This is where CI/CD comes in.

The Problem: The Manual Treadmill πŸƒβ€β™‚οΈ

Imagine every time you fix a bug or add a new feature, you have to manually:

  1. Run all the tests to make sure you didn't break anything.
  2. Build the executable JAR.
  3. Build the Docker image.
  4. Push the new image to a container registry.
  5. Log in to your server and deploy the new version.

This is not only tedious and time-consuming but also prone to human error. What if you forget to run the tests? What if you build the wrong version of the code?

The Solution: CI/CD Pipelines πŸš€

CI/CD stands for Continuous Integration and Continuous Delivery/Deployment.

  • Continuous Integration (CI): The practice of frequently merging code changes from multiple developers into a central repository. After each merge, an automated build and test process is triggered. This helps to catch integration issues early.
  • Continuous Delivery (CD): An extension of CI where the software is automatically built, tested, and prepared for release to production.
  • Continuous Deployment (also CD): Goes one step further and automatically deploys every change that passes all the tests to production.

A CI/CD pipeline is the automated workflow that takes your code from a commit in your repository to a deployed application.

GitHub Actions: Your Automation Butler 🀡

GitHub Actions is a CI/CD platform built right into GitHub. It allows you to automate your workflows directly from your repository. You define your workflows in YAML files in a special .github/workflows directory in your project.

Here's an example of a simple GitHub Actions workflow that builds and tests a Spring Boot application every time you push code to the main branch:

yaml
name: Java CI with Maven

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    - name: Set up JDK 17
      uses: actions/setup-java@v3
      with:
        java-version: '17'
        distribution: 'temurin'
        cache: maven
    - name: Build with Maven
      run: mvn -B package --file pom.xml

Let's break it down:

  • name: Java CI with Maven: The name of the workflow.
  • on:: This defines the events that will trigger this workflow. In this case, it's a push or pull_request to the main branch.
  • jobs:: A workflow is made up of one or more jobs.
  • build job:
    • runs-on: ubuntu-latest: This specifies that the job will run on a virtual machine with the latest version of Ubuntu.
    • steps:: A job is made up of a sequence of steps.
      • uses: actions/checkout@v3: This is a pre-built action that checks out your repository's code into the runner.
      • uses: actions/setup-java@v3: Another pre-built action that sets up a specific version of Java.
      • run: mvn -B package --file pom.xml: This runs the Maven command to build and test our application.

Taking it a Step Further: Building and Pushing a Docker Image 🐳

Let's extend our workflow to also build a Docker image and push it to a container registry (like Docker Hub).

yaml
# ... (previous part of the workflow) ...

    - name: Build and push Docker image
      uses: docker/build-push-action@v4
      with:
        context: .
        push: true
        tags: your-dockerhub-username/your-app-name:latest

This step uses another community-built action, docker/build-push-action, to handle the Docker-related tasks. You would also need to add steps to log in to your Docker registry.

The Big Picture: A Hands-Off Approach 🧘

With a CI/CD pipeline in place, your workflow as a developer becomes much simpler:

  1. You write some code.
  2. You push it to your GitHub repository.
  3. GitHub Actions automatically runs all the tests.
  4. If the tests pass, it builds your application and a new Docker image.
  5. It then pushes the image to your container registry.
  6. (In a full CD pipeline) It could then automatically trigger a deployment to your servers.

This automation frees you up to focus on what you do best: writing great code. It also provides a safety net, ensuring that every change is tested and that your application is always in a releasable state. It's like having a meticulous and tireless robot assistant working for you 24/7!


Further Reading and Resources πŸ“š

Challenge

Challenge: Orchestrate a Spring Boot Application with Docker Compose

Your task is to create a complete docker-compose.yml file to define and run a multi-container application. The application consists of a Spring Boot service and a PostgreSQL database.

Application Components:

  1. Spring Boot App (app service): This service will be built using a Dockerfile located in the same directory.
  2. PostgreSQL Database (db service): This service will use an official public image from Docker Hub.

Requirements:

For the app service:

  • Name the service app.
  • It should be built from the current directory context (.).
  • Map port 8080 on the host to port 8080 in the container.
  • Configure the following environment variables for its database connection:
    • SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/customerdb
    • SPRING_DATASOURCE_USERNAME: admin
    • SPRING_DATASOURCE_PASSWORD: supersecret
  • Ensure this service only starts after the db service is running.

For the db service:

  • Name the service db.
  • Use the postgres:13 image.
  • Set the following environment variables to initialize the database:
    • POSTGRES_USER: admin
    • POSTGRES_PASSWORD: supersecret
    • POSTGRES_DB: customerdb
  • To ensure data persistence across restarts, mount a named volume called db-data to the container's /var/lib/postgresql/data directory.

Top-Level Configuration:

  • Declare the named volume db-data at the top level of the YAML file.

Expected result

A valid docker-compose.yml file that correctly defines and links the app and db services according to all specified requirements, including build context, image, ports, environment variables, dependencies, and volume mapping.

yaml
version: '3.8'

services:
  app:
    build: .
    ports:
      - "8080:8080"
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/customerdb
      SPRING_DATASOURCE_USERNAME: admin
      SPRING_DATASOURCE_PASSWORD: supersecret
    depends_on:
      - db

  db:
    image: postgres:13
    environment:
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: supersecret
      POSTGRES_DB: customerdb
    volumes:
      - db-data:/var/lib/postgresql/data

volumes:
  db-data:
yaml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.