DEV Community

Cover image for Dockerizing a Java Application with Spring and Maven
baltz
baltz

Posted on

Dockerizing a Java Application with Spring and Maven

Docker has become an essential tool for developers, enabling the creation, deployment, and execution of applications in lightweight and portable containers. In this simple guide, we will explore how to dockerize a Java application using Spring and Maven.

Prerequisites:

Before we begin, make sure you have Docker and Docker Compose installed on your machine. You can download them from the official Docker website (https://www.docker.com/get-started).

Step 1: Project Structure

Organize your Spring project following a conventional structure. Make sure to have a pom.xml file to manage dependencies with Maven.

Step 2: Dockerfile Configuration

Create a file called Dockerfile in the root of your project. This file contains the necessary instructions to build the Docker image of your application. Here's a basic example:

# Use the OpenJDK base image
FROM openjdk:11

# Set the working directory
WORKDIR /app

# Copy the JAR files and necessary resources to the container
COPY target/your-application.jar /app/your-application.jar

# Expose the port that the application is listening on
EXPOSE 8080

# Command to run the application when the container starts
CMD ["java", "-jar", "your-application.jar"]
Enter fullscreen mode Exit fullscreen mode

Make sure to replace "your-application.jar" with the actual name of your JAR file generated by Maven.

Step 3: Docker Image Build

Open the terminal in the root of your project and execute the following command to build the Docker image:

docker build -t your-application:latest .

This command uses the Dockerfile in the current directory (.) to build an image with the tag your-application:latest.

Step 4: Container Execution

Now that the image has been successfully built, you can run a container of your application with the following command:

docker run -p 8080:8080 your-application:latest

This command maps port 8080 from the container to port 8080 on the host machine. Adjust as needed.

By following these simple steps, you have dockerized your Java application with Spring and Maven. Your application is now encapsulated in a Docker container, providing portability and making dependency management easier. Be sure to explore more Docker features and adjust as needed for your specific environment.

Top comments (0)