Docker enables developers to package applications along with their dependencies into portable containers. This approach simplifies deployment across different environments. A common use case involves containerizing a Sprinng Boot or other Java application packaged as an executable JAR file.
Prerequisites
- An executable
.jarfile (e.g.,myapp.jar) - A working Docker installation
- A
Dockerfilein the project root
Writing the Dockerfile
The Dockerfile defines the steps to build the image. Below is a minimal and efficient example:
FROM eclipse-temurin:17-jre-alpine
WORKDIR /app
COPY myapp.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
This configuration:
- Uses a lightweight JDK 17 JRE base image (
eclipse-temurin:17-jre-alpine) - Sets
/appas the working directory inside the container - Copies the local JAR into the container as
app.jar - Defines the startup command using
ENTRYPOINTfor better signal handling
Building the Image
From the directory containing both the JAR and the Dockerfile, run:
docker build -t my-java-app .
This creates a Docker image tagged as my-java-app.
Running the Container
To start the container and expose the application port (assuming it listens on port 8080):
docker run -d --name my-running-app -p 8080:8080 my-java-app
The application will now be accessible at http://localhost:8080. The -d flag runs the container in detached mode.