Dockerizing Spring Boot Applications
Docker packages your Spring Boot app with its dependencies into a portable container that runs anywhere.
Multi-Stage Dockerfile
# Stage 1: Build
FROM eclipse-temurin:21-jdk AS builder
WORKDIR /app
COPY pom.xml mvnw ./
COPY .mvn .mvn
RUN ./mvnw dependency:resolve
COPY src src
RUN ./mvnw package -DskipTests
# Stage 2: Run
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
# Non-root user
RUN groupadd -r appuser && useradd -r -g appuser appuser
USER appuser
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
docker build -t bookstore-api .
docker run -p 8080:8080 bookstore-api
Docker Compose — Full Stack
services:
app:
build: .
ports:
- "8080:8080"
environment:
SPRING_PROFILES_ACTIVE: prod
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/bookstore
SPRING_DATASOURCE_USERNAME: admin
SPRING_DATASOURCE_PASSWORD: secret
SPRING_DATA_REDIS_HOST: redis
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
postgres:
image: postgres:16
environment:
POSTGRES_DB: bookstore
POSTGRES_USER: admin
POSTGRES_PASSWORD: secret
ports:
- "5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U admin -d bookstore"]
interval: 5s
timeout: 5s
retries: 5
redis:
image: redis:7
ports:
- "6379:6379"
volumes:
pgdata:
docker compose up -d
docker compose logs -f app
Spring Boot Docker Support (Buildpacks)
Spring Boot can build optimized images without a Dockerfile:
./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=bookstore-api
Uses Cloud Native Buildpacks — creates layered, optimized images automatically.
Jib — Build Without Docker
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>3.4.1</version>
<configuration>
<to>
<image>registry.example.com/bookstore-api</image>
</to>
</configuration>
</plugin>
./mvnw jib:dockerBuild # build to local Docker
./mvnw jib:build # push to registry (no Docker needed)
Image Optimization Tips
| Tip | Impact |
|---|---|
Use eclipse-temurin:21-jre (not JDK) |
~200MB smaller |
| Multi-stage build | Build tools not in final image |
| Layer dependencies separately | Docker cache reuse |
| Non-root user | Security best practice |
.dockerignore |
Exclude target/, .git/, etc. |
.dockerignore:
target/
.git/
.idea/
*.iml
.env
Key Takeaways
- Multi-stage builds — build with JDK, run with JRE.
- Docker Compose for full-stack local development (app + DB + Redis).
- Spring Boot Buildpacks create optimized images without Dockerfiles.
- Jib builds images without Docker installed.
- Always run as a non-root user in production containers.
What’s Next?
Next: Async Processing — @Async, CompletableFuture, and non-blocking operations.