Spring Boot Tutorial
Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)
Prerequisite (Spring Core Concepts)
Spring Boot Core
Spring Boot with REST API
Spring Boot with Database and Data JPA
Spring Boot with Kafka
Spring Boot with AOP
Creating a Spring Boot application and containerizing it using a Dockerfile can be achieved with the following steps:
Create a Spring Boot Application: You can use Spring Initializr to bootstrap a new Spring Boot application. Let's assume you have created a simple web application.
Build Your Application:
Navigate to the root directory of your Spring Boot application and build it using Maven or Gradle. This will produce a .jar
file.
mvn clean install
Dockerfile:
Create a file named Dockerfile
in the root directory of your application. Add the following content to this file:
# Start with a base image containing Java runtime (Choose your preference) FROM openjdk:11-jre-slim # The application's .jar file ARG JAR_FILE=target/*.jar # Copy the application's .jar to the container COPY ${JAR_FILE} app.jar # Specify the default command to run on boot ENTRYPOINT ["java","-jar","/app.jar"]
Dockerfile
starts with a lightweight Java 11 base image.jar
command.Build Docker Image:
Navigate to the directory containing the Dockerfile
and run the following command to build your Docker image:
docker build -t my-spring-boot-app .
This will create a Docker image named my-spring-boot-app
.
Run Your Containerized Application: Once the image is built, you can run it:
docker run -p 8080:8080 my-spring-boot-app
This command maps port 8080
inside the container to port 8080
on your host or local machine.
Access the Application:
If everything is set up correctly, you should be able to access your Spring Boot application by navigating to http://localhost:8080
in your browser or using a tool like curl
.
Bonus Tips:
By following these steps, you've containerized a Spring Boot application, making it easier to deploy, scale, and manage in various environments, from local development to cloud platforms.
Building a Docker image for Spring Boot application:
# Use the official OpenJDK image as the base image FROM openjdk:11-jre-slim # Set the working directory in the container WORKDIR /app # Copy the JAR file into the container COPY target/my-spring-app.jar /app/ # Define the command to run the application CMD ["java", "-jar", "my-spring-app.jar"]
Configuring a Dockerfile for Spring Boot and Maven:
FROM maven:3.8.4-openjdk-11 AS builder WORKDIR /app COPY . /app RUN mvn clean install FROM openjdk:11-jre-slim WORKDIR /app COPY --from=builder /app/target/my-spring-app.jar /app/ CMD ["java", "-jar", "my-spring-app.jar"]
Adding environment variables to Dockerfile for Spring Boot:
FROM openjdk:11-jre-slim ENV DATABASE_URL=jdbc:mysql://localhost:3306/mydb
Configuring ports and networking in a Spring Boot Dockerfile:
FROM openjdk:11-jre-slim EXPOSE 8080