Dockerize your SpringBoot Application

Mintesnot

Last Update 4 years ago

Spring Boot is the world’s leading Java web framework. It’s open source, microservices-based, and helps developers to build scalable Java apps. Developers love Spring because of its auto-configuration, embedded servers, and simplified dependency management. It helps development teams create services faster and more efficiently. Accordingly, users spend very little time on initial setup. That includes downloading essential packages or application servers.

The biggest challenge that developers face with Spring Boot is concurrency — or the need to do too many things simultaneously. Spring Boot may also unnecessarily increase the deployment binary size with unused dependencies. This creates bloated JARs that may increase your overall application footprint while impacting performance. Other challenges include a high learning curve and complexity while building a customized logging mechanism.

How can you offset these drawbacks? Docker simplifies and accelerates your workflows by letting you freely innovate with your choice of tools, application stacks, and deployment environments for each project. You can run your Spring Boot artifact directly within Docker containers. This is useful when you need to quickly create microservices. Let’s see this process in action.

This walkthrough will show you how to accelerate your application development using Spring Boot.
First, we’ll create a simple web app with Spring Boot, without using Docker. Next, we’ll build a Docker image just for that application. You’ll also learn how Docker Compose can help you rapidly deploy your application within containers. Let’s get started.

Key Components

  • JDK 17+
  • Spring Boot CLI (optional)
  • Microsoft Visual Studio Code
  • Docker Desktop

Getting Started

This walkthrough will show you how to accelerate your application development using Spring Boot.

First, we’ll create a simple web app with Spring Boot, without using Docker. Next, we’ll build a Docker image just for that application. You’ll also learn how Docker Compose can help you rapidly deploy your application within containers. Let’s get started.

Once you’ve installed the Maven and OpenJDK package in your system, follow these steps to build a simple web application using Spring Boot.

Spring Initializer

Spring Initializr is a quickstart generator for Spring projects. It provides an extensible API to generate JVM-based projects with implementations for several common concepts — like basic language generation for Java, Kotlin, and Groovy. Spring Initializr also supports build-system abstraction with implementations for Apache Maven and Gradle. Additionally, It exposes web endpoints to generate an actual project and serve its metadata in a well-known format. This lets third-party clients provide assistance where it’s needed.

Open this pre-initialized project in order to generate a ZIP file. Here’s how that looks:

For this demonstration, we’ve paired Maven build automation with Java, a Spring Web dependency, and Java 17 for our metadata.

Click “Generate” to download “spring-boot-docker.zip”. Use the unzip command to extract your files.

Project Structure

The pom.xml file is the core of a Maven project’s configuration. It’s a single configuration file that contains most of the information needed to build a customized project. The POM is huge and can seem daunting. Thankfully, you don’t yet need to understand every intricacy to use it effectively. Here’s your project’s POM:

The SpringbootDockerApplication.java file starts by declaring your com.example.springbootdocker package and importing necessary Spring frameworks. Many Spring Boot developers like their apps to use auto-configuration, component scanning, and extra configuration definitions to their “application class.” You can use a single @SpringBootApplication annotation to enable those features. That same annotation also triggers component scanning for your current package and its sub-packages. You can configure this and even move it elsewhere by manually specifying the base package.

Let’s create a simple RESTful web service that displays “Hello World!” by annotating classic controllers as shown in the following example:.

@RestControler and @RequestMapping are two other popular annotations. The @RestController annotation simplifies the creation of RESTful web services. It conveniently combines @Controller and @ResponseBody — which eliminates the need to annotate every request-handling method of the controller class with the @ResponseBody annotation. Meanwhile, the @RequestMapping annotation maps web requests to Spring Controller methods.

First, we can flag a class as a @SpringBootApplication and as a @RestController, letting Spring MVC harness it for web requests. @RequestMapping maps / to the home() method, which sends a Hello World response. The main() method uses Spring Boot’s SpringApplication.run() method to launch an application.

The following command takes your compiled code and packages it into a distributable format, like a JAR:

./mvnw package

Running the JAR file

After successfully building your JAR, it’s time to run the app package as a JAR file:

java -jar target/spring-boot-docker-0.0.1-SNAPSHOT.jar

Here are the results:

You can now access your “Hello World” page through your web browser at http://localhost:8080, or via this curl command:

Containerizing the SpringBoot Application

Docker helps you containerize your Java app — letting you bundle together your complete Spring application, runtime, configuration, and OS-level dependencies. This includes everything needed to ship a cross-platform, multi-architecture web application.

Let’s assess how you can easily run this app inside a Docker container using a Docker Official Image. First, you’ll need to download Docker Desktop. Docker Desktop accelerates the image-building process while making useful images more discoverable. Complete the installation process once your download is finished.

Docker uses a Dockerfile to specify each image’s “layers.” Each layer stores important changes stemming from the base image’s standard configuration. Create the following empty Dockerfile in your Spring Boot project.

touch Dockerfile

Use your favorite text editor to open this Dockerfile. You’ll then need to define your base image.

Whenever you are creating a Docker image to run a Java program, it’s always recommended to use a smaller base image that helps in speeding up the build process and launching containers at a faster pace. Also, for executing a simple program, we just need to use JRE instead of JDK since there is no development or compilation of the code required.

The upstream Java JDK doesn’t distribute an official JRE package. Hence, we will leverage the popular eclipse-temurin:17-jdk-focal Docker image available in Docker Hub. The Eclipse Temurin project provides code and processes that support the building of runtime binaries and associated technologies that are high-performance, enterprise-caliber & cross-platform.

Next, let’s quickly create a directory to house our image’s application code. This acts as the working directory for your application:

The following COPY instruction copies the Maven wrappers and pom file from the host machine to the container image.The pom.xml file contains information of project and configuration information for the maven to build the project such as dependencies, build directory, source directory, test source directory, plugin, goals etc.

The following RUN instructions trigger a goal that resolves all project dependencies including plugins and reports and their dependencies.

Next, we need to copy the most important directory of the maven project – /src. It includes java source code and pre-environment configuration files of the artifact.

The Spring Boot Maven plugin includes a run goal that can be used to quickly compile and run your application. The last line tells Docker to compile and run your app packages.

Here’s your complete Dockerfile:

Building your Docker Image

Next, you’ll need to build your Docker image. Enter the following command to kickstart this process, which produces an output soon after:

Docker Desktop’s intuitive dashboard lets you manage your containers, applications, and images directly from within Docker Desktop. The GUI enables this with only a few clicks. While still possible, you won’t need to use the CLI to perform these core actions.

Select Dashboard from the top whale menu icon to access the Docker Dashboard:

Click on Images. The Images view displays a list of your Docker images, and lets you run images as functional containers.

Additionally, you can push your images directly to Docker Hub for easy sharing and collaboration.

The Image view also includes the Inspect option. This unveils environmental variables, port information, and more. Crucially, the Image view lets you run your container directly from your image. Simply specify the container’s name, exposed ports, and mounted volumes as required.

Run the Docker SpringBoot Container

Docker runs processes in isolated containers. A container is a process that runs on a host, which is either local or remote. When an operator executes docker run, the container process that runs is isolated with its own file system, networking, and separate process tree from the host.

The following docker run command first creates a writeable container layer over the specified image, and then starts it.

Here is the result:

Go to Docker Dashboard and open your app in your browser:

Next, click Logs to observe your app’s behavior:

Docker Dashboard’s Stats tab lets you view CPU consumption, memory usage, disk read vs. write, and network use:

You can also confirm your containerized application’s functionality via the URL http://localhost:8080:

Docker Compose - Multi-Container Apps

We’ve effectively learned how to build a sample Spring Boot app and create associated Docker images. Next, let’s build a multi-container Spring Boot app using Docker Compose.

For this demonstration, you’ll leverage the popular awesome-compose repository.

Cloning the Repository

Change your directory to match the spring-postgres project and you’ll see the following project directory structure:

Let’s also take a peak at our docker compose file:

The compose file defines an application with two services: backend and db. While deploying the application, docker compose maps port 8080 of the backend service container to port 8080 of the host, per your file. Make sure port 8080 on the host isn’t already in use.

Through your compose file, it’s possible to determine environment variables. For example, you can specify connected databases in the backend service. With a database, you can define the name, password, and parameters of your database.

Thanks to our compose file’s behavior — which lets us recreate containers from indicated services — it’s important to define volumes that store critical information.

Start your application by running docker compose command:

Your container list should show two containers running and their port mappings, as seen below:

After the application starts, navigate to http://localhost:8080http://localhost:8080 in your web browser. You can also run the following curl to form your webpage:

Stop and Remove Your Containers

You’ve successfully built your sample application—congratulations! However, it’s now time to take things offline. You can do this quickly and easily with the following command:

Alternatively, navigate to the Containers / Apps section from Docker Desktop’s sidebar, hover over each active container, and click the square Stop button. The process takes roughly 10 seconds — shutting your containers down elegantly.

Conclusion

We’ve demonstrated how to containerize our Spring Boot application, and why that’s so conducive to smoother deployment. We’ve also harnessed Docker Compose to construct a simple, two-layered web application. This process is quick and lets you devote precious time to other development tasks — especially while using Docker Desktop. No advanced knowledge of containers or even Docker is needed to succeed.

References

Was this article helpful?

0 out of 0 liked this article