Packaging and running the jar

Spring Boot · lesson 15 of 39 · 3 min read

Build a self-contained executable jar, override settings at launch, and containerise it.

Open this lesson in the learning hub

Key points

  • spring-boot-maven-plugin repackages your jar into an executable one with all dependencies inside.
  • ./mvnw clean package then java -jar target/app.jar. No app server to install anywhere.
  • Any property can be overridden at launch: --server.port=9000 as an arg, or SERVER_PORT=9000 as an env var.
  • Pick the profile at deploy time with SPRING_PROFILES_ACTIVE=prod. Same artifact, every environment.
  • ./mvnw spring-boot:build-image builds an OCI image with Buildpacks — no Dockerfile to maintain.
  • In a hand-written Dockerfile, copy dependencies in an earlier layer than your classes so rebuilds stay small.

Example

# Build the executable jar
./mvnw clean package

# Run it
java -jar target/shop-service-1.0.0.jar

# Override anything at launch
java -jar target/shop-service-1.0.0.jar --server.port=9000
SPRING_PROFILES_ACTIVE=prod DB_PASSWORD=secret java -jar target/shop-service-1.0.0.jar

# Build an OCI image without writing a Dockerfile
./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=shop-service:1.0.0

docker run -p 8080:8080 \
  -e SPRING_PROFILES_ACTIVE=prod \
  -e DB_PASSWORD=secret \
  shop-service:1.0.0

# Check it is alive
curl -s localhost:8080/actuator/health

One jar, one command, and every environment difference passed in from outside.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Boot course, and every lesson in it is listed on the Spring Boot contents page.