Skip to main content

Dockerizing Spring Boot

Shipping JARs is so 2010. We ship Images.

1. The Easy Way: Cloud Native Buildpacks

Spring Boot has built-in Docker support. No Dockerfile needed!
./mvnw spring-boot:build-image
This creates an image named demo:0.0.1-SNAPSHOT using optimized layed JARs.

2. The Manual Way: Dockerfile

If you need custom control.
# Stage 1: Build
FROM eclipse-temurin:17-jdk-alpine as build
WORKDIR /app
COPY mvnw .
COPY .mvn .mvn
COPY pom.xml .
COPY src src
RUN ./mvnw install -DskipTests

# Stage 2: Run
FROM eclipse-temurin:17-jre-alpine
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
Build it: docker build -t my-app .

3. Docker Compose for Development

Spin up your whole stack: Postgres, RabbitMQ, Zipkin, and your Apps. docker-compose.yml:
version: '3.8'
services:
  postgres:
    image: postgres:15
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
    ports:
      - "5432:5432"

  rabbitmq:
    image: rabbitmq:management
    ports:
      - "5672:5672"
      - "15672:15672"

  zipkin:
    image: openzipkin/zipkin
    ports:
      - "9411:9411"

  user-service:
    build: ./user-service
    ports:
      - "8081:8080"
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/userdb
    depends_on:
      - postgres
      - rabbitmq
Run: docker-compose up -d

4. Jib (Google’s Plugin)

Builds optimized Docker images without a Docker daemon! Great for CI/CD pipelines. Add plugin to pom.xml:
<plugin>
    <groupId>com.google.cloud.tools</groupId>
    <artifactId>jib-maven-plugin</artifactId>
    <version>3.3.1</version>
</plugin>
Run: ./mvnw jib:dockerBuild