Spring Boot – Docker Deployment

Let’s get started with Docker by building a simple Spring Boot project using Spring Initializer and Dockerizing it step by step.

Github Project link – https://github.com/kuldeep101990/Spring-docker-demo

Step 1: Create a Spring Boot Project

  1. Go to Spring Initializer.
  2. Configure the project:
    • Project: Maven
    • Language: Java
    • Spring Boot Version: Latest stable version
    • Dependencies: Add Spring Web and Spring Boot DevTools
    • Group: com.example
    • Artifact: docker-demo
    • Name: docker-demo
  3. Click Generate to download the project, extract it, and open it in your IDE.

Step 2: Add a Simple REST Endpoint

  1. Create a new package com.example.dockerdemo.controller.
  2. Add a class HelloController:
package com.example.dockerdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

  1. Run the application and test it:
    • Run the project in your IDE or using ./mvnw spring-boot:run.
    • Open your browser or use Postman to visit: http://localhost:8080/hello.

Step 3: Create a Dockerfile

  1. In the root of your project, create a file named Dockerfile (no extension).
  2. Add the following content:
# Use an official Java runtime as a parent image
FROM openjdk:17-jdk-slim

# Set the working directory
WORKDIR /app

# Copy the built JAR file to the container
COPY target/docker-demo-0.0.1-SNAPSHOT.jar app.jar

# Expose the application port
EXPOSE 8080

# Run the application
ENTRYPOINT ["java", "-jar", "app.jar"]


Step 4: Build the Spring Boot Application

  1. Open your terminal in the project root.
  2. Run: ./mvnw clean package
  3. Ensure the target folder contains the docker-demo-0.0.1-SNAPSHOT.jar file.

Step 5: Build and Run the Docker Image

  1. Build the Docker image: docker build -t docker-demo .
  2. Run the Docker container: docker run -p 8080:8080 docker-demo
  3. Test your application:
    • Visit http://localhost:8080/hello to see the “Hello, Docker!” message.

Step 6: Stop and Remove the Container

  1. List running containers: docker ps
  2. Stop the container: docker stop <container-id>
  3. Remove the container: docker rm <container-id>

Let me know when you’re ready for more advanced Docker features like Docker Compose or multi-stage builds! πŸš€

Leave a Reply

Your email address will not be published. Required fields are marked *