Docker for Java developers
A practical guide to containerizing Spring Boot applications and deploying scalable solutions.
A practical guide to containerizing Spring Boot applications and deploying scalable solutions.
1 min read
Computer Engineer specializing in the Java/Spring ecosystem. Expert in microservice optimization, legacy architecture migration, and deployment of scalable solutions with Docker. Focused on improving operational efficiency and reducing resource consumption through automation.
In this article you will learn how to containerize a Spring Boot application with Docker, from scratch.
Docker lets you package your application with all its dependencies into a portable container. This eliminates the classic "it works on my machine" problem.
FROM eclipse-temurin:21-jdk-alpine
WORKDIR /app
COPY target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
To reduce the image size, we use a multi-stage build:
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /app
COPY . .
RUN mvn clean package -DskipTests
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
With docker-compose you can bring up your database and your API together:
services:
db:
image: postgres:16
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
app:
build: .
ports:
- "8080:8080"
depends_on:
- db
Containerizing your Java application is not complicated. Start with a simple Dockerfile and evolve to multi-stage builds when size matters.