Before we use docker inside the spring boot application first we need to install the Docker Desktop. Please follow below steps for the installation.
Docker is an open-source containerization platform that allows you to package your application and its dependencies into a portable container. In this article, we will explore how to containerize a Spring Boot application using Docker.
First we need to create the spring boot application. Please refer the following SpringBoot CRUD Example session to create a sample spring boot application. Once we created the sample spring boot application then in the same application next we need to create the docker file.
A Dockerfile is a text file that contains a set of instructions for creating a Docker image. In this section, we will create a Dockerfile for our Spring Boot application. Create a new file called Dockerfile in the root directory of your Spring Boot application. Here’s an example Dockerfile:
FROM openjdk:17-jdk-slim
WORKDIR /opt/app
ARG JAR_FILE=target/sb-crud-with-docker-example-0.0.1-SNAPSHOT.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","app.jar"]
Now that we have created a Dockerfile, we can use it to build a Docker image for our Spring Boot application.
Open a terminal or command prompt and navigate to the root directory of your Spring Boot application. Run the following command to build the Docker image:
docker build -t app .
This command will build a Docker image with the tag app. The . at the end of the command specifies the build context, which is the current directory.
To run a containerized application, we need to start a Docker container using the Docker image that we built in the previous step.
Run the following command to start a new Docker container:
docker run -p 8086:8086 app
This command starts a new Docker container using the app image and maps port 8086 in the container to port 8086 on the host machine. The containerized application should now be accessible at http://localhost:8086/api/v1/customer/getAll
Docker provides a powerful set of tools for managing containerized applications. Here are some of the most useful Docker commands for managing containers:
Full source code is available in follwong GitHub repository: SpringBoot with Docker