Java Deployment

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 284 of 306

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.

OptionWhat you shipNeeds Java on the target?Typical use
Executable JAROne .jar fileYesSpring Boot apps, tools, microservices
WAR file.war deployed into Tomcat or GlassFishYes, plus a serverServlet and Jakarta EE apps
JAR + custom runtime (jlink)JAR plus a trimmed Java runtime folderNoSmall, self-contained server installs
Native installer (jpackage).deb, .rpm, .msi, .dmg or app folderNoDesktop apps, apps for non-developers
Container imageDocker image with Java + JARNo (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.
  • /health lets 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 the out folder. The jar tool 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.jar tells 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=prod sets environment variables for this one command. On a server you put them in a file or a service definition instead.
  • -Xms128m -Xmx256m sets 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

SourceExampleRead in Java with
Environment variableAPP_PORT=9091System.getenv("APP_PORT")
System propertyjava -Dapp.port=9091 -jar ...System.getProperty("app.port")
Command-line argumentjava -jar app.jar 9091args[0]
Config file/etc/course-server/app.propertiesProperties.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.base holds core classes such as String and Instant. jdk.httpserver holds com.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.

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 runtime folder 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 jdeps cannot see, such as java.sql or jdk.crypto.ec. If you get ClassNotFoundException at 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-image creates a ready-to-run folder. bin/course-server is a native launcher, so users start the app without typing java -jar.
  • --runtime-image runtime reuses the jlink runtime from Step 4. Without it, jpackage runs jlink for you with a larger default module set.
  • Change --type to deb, rpm, msi, exe, dmg or pkg to build an installer. Each type must be built on its own operating system (an .msi on Windows, a .dmg on macOS).

Java Deployment Checklist for Servers

StepWhy it matters
Use a supported LTS JDK (21 or 25)Security fixes keep coming for years
Put the version in the manifest and file nameYou always know what is running
Read config from env vars or filesOne build for dev, test and production
Set -XmxThe JVM does not take more memory than planned
Add a /health endpointScripts and load balancers can check the app
Handle SIGTERM with a shutdown hookRestarts do not cut requests in half
Write logs to stdout or a log fileYou can see errors after the fact
Keep old releasesYou 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:

  1. Versioned releases. Each version gets its own folder under releases/, and nothing is overwritten. The server keeps a history of exactly what was deployed.
  2. One switch point. ln -sfn changes the current link in a single step. app.sh always starts current/app.jar, so it never needs to know version numbers.
  3. Health-gated deploy. The script waits up to 10 seconds for /health to answer. A deploy only counts as successful when the new version is actually serving requests and reports its version.
  4. Automatic rollback. Version 1.2.0 crashed on start (Could not find or load main class appears in the log), so the health check never passed. The script pointed current back at 1.1.0 and restarted it, and the exit code 1 tells a CI pipeline that the deploy failed.
  5. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Deployment and get answers drawn from it.

Signed-in readers only.