Skip to main content
Advertisement

18.1 Dockerizing a Spring Boot Application

1. Writing a Dockerfile (Multi-Stage Build)

Multi-stage builds exclude build tools (Gradle, JDK) from the final image, keeping only the minimal JRE and JAR needed to run — dramatically reducing image size.

# ─── Stage 1: Build ───
FROM gradle:8.6-jdk21 AS builder
WORKDIR /app
COPY . .
RUN gradle bootJar --no-daemon

# ─── Stage 2: Runtime (final image) ───
FROM eclipse-temurin:21-jre-jammy
WORKDIR /app

# Security: run as non-root user
RUN addgroup --system spring && adduser --system --ingroup spring spring
USER spring:spring

COPY --from=builder /app/build/libs/*-SNAPSHOT.jar app.jar

ENV TZ=Asia/Seoul
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

2. Docker Compose — Unified Local Development Environment

services:
app:
build: .
ports:
- "8080:8080"
environment:
- SPRING_DATASOURCE_URL=jdbc:mysql://db:3306/tododb
- SPRING_DATASOURCE_USERNAME=root
- SPRING_DATASOURCE_PASSWORD=secret
- SPRING_DATA_REDIS_HOST=redis
depends_on:
db:
condition: service_healthy
redis:
condition: service_started

db:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: tododb
ports:
- "3306:3306"
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
retries: 5

redis:
image: redis:7.0
ports:
- "6379:6379"

A single docker compose up --build gives you a complete dev environment with the app, MySQL, and Redis running together.

Advertisement