Java Deployment
Java deployment is the work of taking an application from your laptop and running it reliably on a server or a user's machine. It covers how you package the code, which Java runtime runs it, where its settings come from, and how you start, check and stop it. Getting these steps right means the same build behaves the same way in testing and in production.
This lesson gives an overview of Java deployment with one small example application that is packaged and run in several ways. The following lessons go deeper into JAR deployment, WAR deployment, running as a service and Docker. All commands were run with JDK 21; they work the same on newer JDKs.
Java Deployment Options Compared
There are five common ways to ship a Java application.
| Option | What you ship | Needs Java on the target? | Typical use |
|---|---|---|---|
| Executable JAR | One .jar file | Yes | Spring Boot apps, tools, microservices |
| WAR file | .war deployed into Tomcat or GlassFish | Yes, plus a server | Servlet and Jakarta EE apps |
JAR + custom runtime (jlink) | JAR plus a trimmed Java runtime folder | No | Small, self-contained server installs |
Native installer (jpackage) | .deb, .rpm, .msi, .dmg or app folder | No | Desktop apps, apps for non-developers |
| Container image | Docker image with Java + JAR | No (Docker instead) | Cloud and Kubernetes |
How it works:
- Every option starts from the same compiled classes. They differ in what else travels with your code: nothing, an app server, a Java runtime or a whole operating system layer.
- Most modern server apps ship as an executable JAR or a container image. WAR files remain common where companies already run application servers, as shown in Jakarta EE.
The Example Application
The examples use a tiny HTTP server built only with the JDK, so nothing has to be downloaded. It serves a course list and a /health endpoint.
package com.gocourse.app;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
public class CourseServer {
public static void main(String[] args) throws IOException {
// configuration comes from the environment, not from the code
int port = Integer.parseInt(System.getenv().getOrDefault("APP_PORT", "8080"));
String environment = System.getenv().getOrDefault("APP_ENV", "dev");
String version = CourseServer.class.getPackage().getImplementationVersion();
Instant startedAt = Instant.now();
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/api/courses", exchange ->
send(exchange, 200, "[\"java\",\"go\",\"html\"]"));
server.createContext("/health", exchange -> {
long uptime = Duration.between(startedAt, Instant.now()).toSeconds();
send(exchange, 200, "{\"status\":\"UP\",\"version\":\"" + version
+ "\",\"env\":\"" + environment + "\",\"uptimeSeconds\":" + uptime + "}");
});
// stop cleanly when the process receives SIGTERM (Ctrl+C, kill, systemctl stop)
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Shutting down...");
server.stop(2);
System.out.println("Stopped.");
}));
server.start();
System.out.printf("CourseServer %s started on port %d (env=%s, java=%s)%n",
version, port, environment, Runtime.version().feature());
}
private static void send(HttpExchange exchange, int status, String json) throws IOException {
byte[] body = json.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(status, body.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(body);
}
}
}
How it works:
- The port and environment name are read from environment variables with safe defaults. The code never contains server-specific values.
- The version is read from the JAR's manifest (
Implementation-Version), so the running app always knows which release it is. - The shutdown hook runs when the process is asked to stop, giving open requests up to two seconds to finish.
/healthlets scripts, load balancers and monitoring tools check that the app is alive.
Step 1: Build an Executable JAR
An executable JAR has a Main-Class entry in its manifest. Here the manifest also carries the version.
Main-Class: com.gocourse.app.CourseServer
Implementation-Title: course-server
Implementation-Version: 1.0.0
javac -d out src/com/gocourse/app/CourseServer.java
jar --create --file course-server-1.0.0.jar --manifest manifest.txt -C out .
ls -l course-server-1.0.0.jar
unzip -p course-server-1.0.0.jar META-INF/MANIFEST.MF
-rw-r--r-- 1 asha asha 3090 Nov 18 10:15 course-server-1.0.0.jar
Manifest-Version: 1.0
Main-Class: com.gocourse.app.CourseServer
Implementation-Title: course-server
Implementation-Version: 1.0.0
Created-By: 21.0.12 (Ubuntu)
How it works:
-C out .adds every compiled class from theoutfolder. Thejartool merges your manifest lines with its own (Manifest-Version,Created-By).- Put the version in the file name too. When a server has several releases,
course-server-1.0.0.jartells you instantly what it is. - Real projects build the same JAR with Maven or Gradle, including dependencies, as shown in Build executable JAR in Java.
Step 2: Run the JAR With External Configuration
The same JAR runs in every environment. Only the configuration around it changes.
APP_PORT=9091 APP_ENV=prod java -Xms128m -Xmx256m -jar course-server-1.0.0.jar
CourseServer 1.0.0 started on port 9091 (env=prod, java=21)
In a second terminal:
curl -s -w "\n" http://localhost:9091/health
curl -s -w "\n" http://localhost:9091/api/courses
{"status":"UP","version":"1.0.0","env":"prod","uptimeSeconds":2}
["java","go","html"]
Press Ctrl+C in the first terminal:
^CShutting down...
Stopped.
How it works:
APP_PORT=9091 APP_ENV=prodsets environment variables for this one command. On a server you put them in a file or a service definition instead.-Xms128m -Xmx256msets the starting and maximum heap. Without-Xmx, the JVM takes up to a quarter of the machine's memory, which can be too much on a shared server.- Ctrl+C sends a signal that triggers the shutdown hook, so the server closes cleanly instead of being cut off.
Where Configuration Can Come From
| Source | Example | Read in Java with |
|---|---|---|
| Environment variable | APP_PORT=9091 | System.getenv("APP_PORT") |
| System property | java -Dapp.port=9091 -jar ... | System.getProperty("app.port") |
| Command-line argument | java -jar app.jar 9091 | args[0] |
| Config file | /etc/course-server/app.properties | Properties.load(...) |
Note: Never put passwords or API keys inside the JAR or in source control. Pass them in at runtime through environment variables or a secrets store, so a leaked JAR file does not leak your database password.
Step 3: Check Which Java Modules the App Needs
jdeps analyses a JAR and lists the JDK modules it uses. That list is the input for a custom runtime.
jdeps --print-module-deps course-server-1.0.0.jar
java.base,jdk.httpserver
How it works:
java.baseholds core classes such asStringandInstant.jdk.httpserverholdscom.sun.net.httpserver.HttpServer.- A full JDK has around 70 modules. This app needs just 2, which means most of the JDK is dead weight on the server.
Step 4: Ship a Custom Runtime With jlink
jlink builds a trimmed Java runtime containing only the modules you name. The target machine then needs no Java installation at all.
jlink --add-modules java.base,jdk.httpserver \
--strip-debug --no-header-files --no-man-pages \
--output runtime
du -sh runtime /usr/lib/jvm/java-21-openjdk-amd64
runtime/bin/java --list-modules
53M runtime
286M /usr/lib/jvm/java-21-openjdk-amd64
java.base@21.0.12
jdk.httpserver@21.0.12
APP_PORT=9092 runtime/bin/java -jar course-server-1.0.0.jar
CourseServer 1.0.0 started on port 9092 (env=dev, java=21)
How it works:
- The custom runtime is about 53 MB instead of 286 MB for the full JDK, and it contains only the two needed modules.
- Copy the
runtimefolder and the JAR to the server together. Every server then runs the exact Java version you tested with. - A runtime built on Linux runs only on Linux (with the same CPU type). Build it on the same operating system you deploy to.
Note: Apps that use reflection-heavy libraries may need extra modules that
jdepscannot see, such asjava.sqlorjdk.crypto.ec. If you getClassNotFoundExceptionat runtime, add the missing module to--add-modules.
Step 5: Create an Installable App With jpackage
jpackage wraps your JAR and a runtime into a native application: a launcher program, or an installer such as .deb, .rpm, .msi or .dmg.
mkdir -p input && cp course-server-1.0.0.jar input/
jpackage --type app-image \
--name course-server --app-version 1.0.0 \
--input input --main-jar course-server-1.0.0.jar \
--runtime-image runtime \
--dest dist
find dist -maxdepth 3
dist
dist/course-server
dist/course-server/bin
dist/course-server/bin/course-server
dist/course-server/lib
dist/course-server/lib/app
dist/course-server/lib/runtime
dist/course-server/lib/course-server.png
dist/course-server/lib/libapplauncher.so
APP_PORT=9094 dist/course-server/bin/course-server
CourseServer 1.0.0 started on port 9094 (env=dev, java=21)
How it works:
--type app-imagecreates a ready-to-run folder.bin/course-serveris a native launcher, so users start the app without typingjava -jar.--runtime-image runtimereuses the jlink runtime from Step 4. Without it, jpackage runs jlink for you with a larger default module set.- Change
--typetodeb,rpm,msi,exe,dmgorpkgto build an installer. Each type must be built on its own operating system (an.msion Windows, a.dmgon macOS).
Java Deployment Checklist for Servers
| Step | Why it matters |
|---|---|
| Use a supported LTS JDK (21 or 25) | Security fixes keep coming for years |
| Put the version in the manifest and file name | You always know what is running |
| Read config from env vars or files | One build for dev, test and production |
Set -Xmx | The JVM does not take more memory than planned |
Add a /health endpoint | Scripts and load balancers can check the app |
| Handle SIGTERM with a shutdown hook | Restarts do not cut requests in half |
| Write logs to stdout or a log file | You can see errors after the fact |
| Keep old releases | You can roll back in seconds |
How it works:
- Spring Boot apps get most of this for free: version info, Actuator health checks, graceful shutdown and external configuration, as covered in the Spring Boot tutorial.
- Plain Java apps, like the example here, need these few lines added by hand.
Real-World Example: A Java Deployment Script With Health Check
This script does a complete deployment of the example on a Linux server: it copies a new JAR into a versioned folder, points a current link at it, restarts the app and checks /health. If the check fails, it puts the old version back.
#!/usr/bin/env bash
# deploy.sh <jar-file> <version> - install a new release and switch to it
set -euo pipefail
APP_HOME="${APP_HOME:-/opt/course-server}"
JAR_FILE="$1"
VERSION="$2"
RELEASE_DIR="$APP_HOME/releases/$VERSION"
PORT="${APP_PORT:-8080}"
echo "==> Installing $VERSION"
mkdir -p "$RELEASE_DIR"
cp "$JAR_FILE" "$RELEASE_DIR/app.jar"
PREVIOUS=$(readlink "$APP_HOME/current" 2>/dev/null || true)
ln -sfn "$RELEASE_DIR" "$APP_HOME/current" # point "current" at the new release
echo "==> current -> releases/$VERSION"
"$APP_HOME/app.sh" restart
echo "==> Waiting for health check"
for i in $(seq 1 20); do
if curl -fs "http://localhost:$PORT/health" > /dev/null; then
echo "==> Healthy: $(curl -s "http://localhost:$PORT/health")"
exit 0
fi
sleep 0.5
done
echo "==> Health check failed, rolling back"
if [ -n "$PREVIOUS" ]; then
ln -sfn "$PREVIOUS" "$APP_HOME/current"
"$APP_HOME/app.sh" restart
echo "==> Rolled back to $(basename "$PREVIOUS")"
fi
exit 1
The script calls app.sh, a small start/stop script that is explained line by line in the JAR deployment lesson. Deploying version 1.1.0 on a server already running 1.0.0:
cd /opt/course-server
./deploy.sh ~/builds/course-server-1.1.0.jar 1.1.0
==> Installing 1.1.0
==> current -> releases/1.1.0
Stopped
Started (pid 515)
==> Waiting for health check
==> Healthy: {"status":"UP","version":"1.1.0","env":"prod","uptimeSeconds":0}
Deploying a broken build 1.2.0 (its manifest names a class that does not exist):
./deploy.sh ~/builds/course-server-1.2.0.jar 1.2.0; echo "exit=$?"
==> Installing 1.2.0
==> current -> releases/1.2.0
Stopped
Started (pid 626)
==> Waiting for health check
==> Health check failed, rolling back
Not running
Started (pid 694)
==> Rolled back to 1.1.0
exit=1
How it works:
- Versioned releases. Each version gets its own folder under
releases/, and nothing is overwritten. The server keeps a history of exactly what was deployed. - One switch point.
ln -sfnchanges thecurrentlink in a single step.app.shalways startscurrent/app.jar, so it never needs to know version numbers. - Health-gated deploy. The script waits up to 10 seconds for
/healthto answer. A deploy only counts as successful when the new version is actually serving requests and reports its version. - Automatic rollback. Version 1.2.0 crashed on start (
Could not find or load main classappears in the log), so the health check never passed. The script pointedcurrentback at 1.1.0 and restarted it, and the exit code1tells a CI pipeline that the deploy failed. - Same pattern everywhere. The building blocks of Java deployment — a versioned artifact, external config, a health check and a quick way back — stay the same whether you ship a JAR, a WAR or a container image.