DEV Community

Cover image for Crafting Docker Containers for Your Spring Boot Applications
Abassi Sabri
Abassi Sabri

Posted on

Crafting Docker Containers for Your Spring Boot Applications

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.

Spring boot

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"]

Enter fullscreen mode Exit fullscreen mode

Build Docker Image :

docker build -t <image-name> .
Enter fullscreen mode Exit fullscreen mode

Image build

Check The list of images :

docker images
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
  1. 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).

  2. container-port : The port within the container that your application listens on (defaults to 8080 for Spring Boot).

  3. 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
Enter fullscreen mode Exit fullscreen mode

running container

Thx For Reading!

Top comments (0)