If you’re working on a Spring Boot project that targets Java 17, 21, or 24, but your system only has Java 8 (or no Java at all), building the .jar with mvn clean install becomes impossible.
The Problem: We want to
- Build the Spring Boot .jar using Docker (no local Java or Maven)
- Extract only the built .jar to our host system
- Clean up the container, image, and temporary Dockerfile
- Avoid polluting the final image with source code
The Solution: A Simple Bash Script
Here’s a script that does everything for you:
#!/bin/bash
set -e
IMAGE_TAG="spring-boot-builder"
CONTAINER_NAME="spring-builder-temp"
TARGET_DIR="./target"
TMP_DOCKERFILE="Dockerfile.temp"
echo "📝 Creating temporary Dockerfile..."
cat > $TMP_DOCKERFILE <<'EOF'
# Stage 1: Build the jar
FROM eclipse-temurin:24-jdk AS builder
WORKDIR /app
COPY .mvn/ .mvn
COPY mvnw pom.xml ./
RUN ./mvnw dependency:go-offline
COPY src ./src
RUN ./mvnw clean package -DskipTests
# Stage 2: Minimal image with only the built jar
FROM scratch AS final
COPY --from=builder /app/target /app/target
EOF
echo "🔨 Building image..."
podman build -t $IMAGE_TAG -f $TMP_DOCKERFILE .
echo "📦 Creating temporary container..."
podman create --name $CONTAINER_NAME $IMAGE_TAG
echo "📁 Preparing target directory..."
mkdir -p "$TARGET_DIR"
echo "📤 Copying .jar files to $TARGET_DIR..."
podman cp $CONTAINER_NAME:/app/target/. "$TARGET_DIR/"
# delete everything except .jar files
#find "$TARGET_DIR" -type f ! -name "*.jar" -delete
echo "🧹 Cleaning up..."
podman rm $CONTAINER_NAME > /dev/null
podman rmi $IMAGE_TAG > /dev/null
rm -f $TMP_DOCKERFILE
echo "✅ Done. .jar files are available in $TARGET_DIR/"
Note: Replace podman
with docker
in above script if you are using docker
How It Works
- Stage 1 uses a full JDK image to build the .jar
- Stage 2 (FROM scratch) is an empty container that holds only the output
- The script builds the image, creates a container, copies generated classes and jars to ./target, and then deletes all traces
- No Java or Maven is needed on the host
Why This Matters
- Keeps your local system clean
- Works regardless of your installed Java version
- Perfect for CI/CD pipelines or constrained dev environments
- Avoids polluting the image with source code or build artifacts
Requirements
- Docker or Podman installed
- Your Spring Boot project should use the Maven wrapper (mvnw) and have a standard layout
Final Tip
You can drop this script into any Spring Boot project and run:
chmod +x build.sh
./build.sh
And you’ll get a ready-to-deploy .jar in ./target/, without installing anything else.