Introduction
Docker containers offer a lightweight and portable way to package and deploy your Spring Boot applications. This article guides you through the essential steps of creating a Docker container for your Spring Boot project, enabling you to streamline your development and deployment workflows.
Prerequisites
- Docker installed and running on your system. Here !.
- A Spring Boot project with a generated executable JAR file (typically located in target/ directory).
- Basic understanding of Docker concepts.
Create a Dockerfile:
In the root directory of your Spring Boot project, create a plain text file named Dockerfile. This file specifies the instructions for building your Docker image.
Define the Base Image:
The first line in your Dockerfile specifies the base image upon which your Spring Boot application will run. A common choice is openjdk:21-slim (or a similar JDK version) as it provides a lightweight Java runtime environment.
# Dockerfile
FROM openjdk:21-slim
Copy the JAR File:
Use the COPY instruction to copy your Spring Boot application's JAR file from your project directory to a suitable location within the container image.
# Dockerfile
FROM openjdk:21-slim
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
Define the Entrypoint:
The ENTRYPOINT instruction specifies the command to be executed when the container starts. If your Spring Boot application has a main method, you can use the following:
# Dockerfile
FROM openjdk:21-slim
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
Build Docker Image :
docker build -t <image-name> .
Check The list of images :
docker images
Run the Container:
Use the docker run command to start a container from your newly built image. Here's the basic syntax:
docker run -d -p <host-port>:<container-port> <image-name>
host-port: The port on your host machine that will be mapped to the container's application port (usually the default Spring Boot port, 8080).
container-port : The port within the container that your application listens on (defaults to 8080 for Spring Boot).
image-name: The name of your Docker image created.
Example:
docker run -d -p 8081:8081 --name test-microservice test-image
docker ps # list of running containers
Thx For Reading!
Top comments (0)