Deploying Java means producing an artefact and running it somewhere with the right configuration. The artefact is usually a self-contained jar or a container image; the configuration is what separates an application that survives contact with production from one that falls over. This guide covers both.
Building a runnable jar#
With Spring Boot, this is already configured:
./mvnw clean package -DskipTests=false
java -jar target/app-1.0.0.jar
Without it, the shade plugin bundles your dependencies into one file:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.2</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>shade</goal></goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.example.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
Always build the artefact you deploy from a clean checkout in your pipeline, not from a developer’s machine. A jar built from an uncommitted working tree is not reproducible.
Docker#
FROM eclipse-temurin:21-jdk-alpine AS build
WORKDIR /src
COPY .mvn/ .mvn/
COPY mvnw pom.xml ./
RUN ./mvnw dependency:go-offline -B
COPY src/ src/
RUN ./mvnw clean package -DskipTests -B
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
RUN addgroup -S app && adduser -S app -G app
USER app
COPY --from=build /src/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
Three things are doing real work here. The build happens in an image with the JDK while the final image has only the JRE, which is considerably smaller. Copying the pom and resolving dependencies before copying the source means Docker caches that layer, so an ordinary code change rebuilds in seconds. And the application runs as a non-root user.
Spring Boot can split the jar into layers that cache even better:
FROM eclipse-temurin:21-jre-alpine AS extract
WORKDIR /app
COPY target/*.jar app.jar
RUN java -Djarmode=layertools -jar app.jar extract
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=extract /app/dependencies/ ./
COPY --from=extract /app/spring-boot-loader/ ./
COPY --from=extract /app/snapshot-dependencies/ ./
COPY --from=extract /app/application/ ./
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
Dependencies change rarely and your code changes constantly, so separating them means a rebuild pushes a few hundred kilobytes rather than a hundred megabytes.
JVM settings that matter#
java -XX:MaxRAMPercentage=75 \
-XX:+UseG1GC \
-XX:+ExitOnOutOfMemoryError \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/var/log/app \
-jar app.jar
| Flag | Why |
|---|---|
MaxRAMPercentage |
sizes the heap from the container limit, not the host |
UseG1GC |
the default, and worth being explicit about |
ExitOnOutOfMemoryError |
die rather than limp along in an unrecoverable state |
HeapDumpOnOutOfMemoryError |
gives you something to analyse afterwards |
Almost every other tuning flag is workload-specific. Copying a set from a blog post is more likely to hurt than help; change one thing, measure, keep it only if the numbers improve.
Configuration#
spring.datasource.url=jdbc:postgresql://db:5432/shop
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.open-in-view=false
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=30s
export SPRING_PROFILES_ACTIVE=production
export DB_PASSWORD="$(cat /run/secrets/db_password)"
Two of those settings deserve comment. Setting the schema mode to validate rather than update means Hibernate checks the schema matches rather than silently altering your production database — use Flyway or Liquibase for changes. And graceful shutdown lets in-flight requests finish before the process exits, which is what stops a deployment dropping requests.
Running as a service#
[Unit]
Description=My Application
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=app
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/java -XX:MaxRAMPercentage=75 -jar /opt/myapp/app.jar
EnvironmentFile=/etc/myapp/env
Restart=always
RestartSec=10
SuccessExitStatus=143
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/var/log/myapp
[Install]
WantedBy=multi-user.target
sudo systemctl enable --now myapp
sudo journalctl -u myapp -f
SuccessExitStatus=143 matters: 143 is a normal termination by signal, and without this line systemd treats every graceful stop as a failure.
Health checks#
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.probes.enabled=true
management.endpoint.health.show-details=never
/actuator/health/liveness is the process alive
/actuator/health/readiness is it ready for traffic
The distinction matters to an orchestrator. Failing liveness means restart me; failing readiness means stop sending traffic but do not kill me. Wiring both to the same check causes restart loops during a slow database connection.
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s \
CMD wget -qO- http://localhost:8080/actuator/health/readiness || exit 1
Expose only the endpoints you need, and never show-details=always publicly — the detailed response names your database and its status.
Logging#
logging.pattern.console={"time":"%d{ISO8601}","level":"%p","logger":"%c{1}","msg":"%m"}%n
logging.level.root=INFO
logging.level.com.example=DEBUG
Log to standard output, not to a file. In a container the platform collects stdout; writing to a file inside a container means the logs disappear when it restarts.
Structured JSON makes logs searchable. Add a request identifier to the mapped diagnostic context and every line from one request becomes findable:
MDC.put("requestId", UUID.randomUUID().toString());
try {
// handle the request
} finally {
MDC.clear();
}
A pre-deployment checklist#
- Built in CI from a tagged commit, not from a laptop
- Tests ran and passed as part of that build
- No secrets in the image or the repository
- Runs as a non-root user
- Heap sized from the container limit
- Liveness and readiness probes wired separately
- Graceful shutdown enabled
- Logs to stdout, structured
- Schema changes managed by migrations, not by Hibernate
- A current, supported JDK
Questions people ask#
Fat jar or a WAR on an application server?
A fat jar with an embedded server, for almost everything now. It removes a whole layer of configuration and makes the artefact self-contained. WAR deployment persists mainly in older estates.
Alpine or a Debian-based image?
Alpine is smaller. It uses musl rather than glibc, which occasionally affects native libraries. If something behaves oddly, try a Debian-based image before spending long on it.
How much memory does a JVM need?
More than the heap — there is metaspace, thread stacks, code cache and direct buffers on top. Setting the heap to about 75 per cent of the container limit leaves room for the rest.
Does GraalVM native image help?
Start-up drops dramatically and memory use falls, which matters for serverless and short-lived containers. The build is slower and reflection needs configuration, so it suits applications designed for it rather than retrofits.
Where to go next#
- Java web development — what you are deploying.
- Java performance optimization — heap and garbage collection in depth.
- Deployment and packaging — the principles across languages.