You are currently viewing How to Run a Spring Boot App on Docker: A Step-by-Step Guide

How to Run a Spring Boot App on Docker: A Step-by-Step Guide

Introduction

In this tutorial, you’ll learn how to run a Spring Boot application on Docker, leveraging the power of containerization for easier deployment and scalability. Docker allows you to package your application and its dependencies into a standardized unit for seamless deployment across different environments. Let’s dive in!

Prerequisites

Before you begin, ensure you have the following prerequisites installed on your system:

  1. Java Development Kit (JDK)
  2. Maven
  3. Docker Desktop (or Docker Engine)

Step 1: Create a Spring Boot Application

If you haven’t already, create a simple Spring Boot application. For demonstration purposes, we’ll create a basic RESTful service.

// HelloWorldController.java
@RestController
public class HelloWorldController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, Docker!";
    }
}

Step 2: Dockerize Your Application

Now, let’s create a Dockerfile in the root directory of your Spring Boot project. This file contains instructions to build a Docker image for your application.

# Use the official OpenJDK image as a parent image
FROM openjdk:11-jre-slim

# Set the working directory in the container
WORKDIR /app

# Copy the packaged jar file into the container
COPY target/your-application.jar /app

# Expose the port your application runs on
EXPOSE 8080

# Run the jar file
CMD ["java", "-jar", "your-application.jar"]

Replace your-application.jar with the name of your Spring Boot application’s JAR file.

Step 3: Build the Docker Image

Navigate to your project directory in the terminal and run the following command to build the Docker image:

docker build -t your-image-name .

Replace your-image-name with a suitable name for your Docker image.

Step 4: Run the Docker Container

Once the image is built, you can run your Spring Boot application in a Docker container using the following command:

docker run -p 8080:8080 your-image-name

Replace your-image-name with the name of your Docker image.

Step 5: Test Your Application

Your Spring Boot application is now running inside a Docker container. Test it by accessing the endpoint in your web browser or using a tool like cURL:

curl http://localhost:8080/hello

Conclusion

You’ve successfully containerized your Spring Boot application using Docker. This approach makes it easier to deploy and scale your application across different environments with consistency and reliability.

Leave a Reply