JAR Deployment

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

Java JAR deployment means copying an executable JAR to a server and running it with java -jar so it keeps working after you log out, restarts cleanly and can be updated or rolled back safely. It is the simplest way to put a Spring Boot app or any self-contained Java service into production. All you need on the server is a Java runtime, a folder layout and a small start/stop script.

This lesson deploys the CourseServer app from the Java deployment lesson to a Linux server (Ubuntu here) step by step. Every command and output was tested with JDK 21.


What a Java JAR Deployment Needs

PieceExamplePurpose
Executable JARcourse-server-1.1.0.jarYour application with a Main-Class
Java runtimeOpenJDK 21 or a jlink runtimeRuns the JAR
Dedicated usercourseappThe app does not run as root
App folder/opt/course-serverReleases, config, logs and scripts
Config fileapp.envPort, environment name, secrets
Start/stop scriptapp.shStarts in the background, stops cleanly

How it works:

  • The JAR must run on its own with java -jar. If it needs extra libraries, build a fat JAR first, as shown in Build executable JAR in Java. Spring Boot's Maven and Gradle plugins do this automatically.
  • Everything else on this list is set up once per server. Later deployments only copy a new JAR.

Prepare the Server for JAR Deployment

Install Java, create a system user and create the folder layout.

# on the server
sudo apt update
sudo apt install -y openjdk-21-jre-headless
java -version

sudo useradd --system --create-home --home-dir /opt/course-server --shell /usr/sbin/nologin courseapp
sudo -u courseapp mkdir -p /opt/course-server/{releases,logs}
ls -ld /opt/course-server /opt/course-server/*
openjdk version "21.0.12" 2026-07-21
OpenJDK Runtime Environment (build 21.0.12+7-Ubuntu-1ubuntu224.04)
OpenJDK 64-Bit Server VM (build 21.0.12+7-Ubuntu-1ubuntu224.04, mixed mode, sharing)
drwxr-x--- 4 courseapp courseapp 4096 Nov 18 10:20 /opt/course-server
drwxr-xr-x 2 courseapp courseapp 4096 Nov 18 10:20 /opt/course-server/logs
drwxr-xr-x 2 courseapp courseapp 4096 Nov 18 10:20 /opt/course-server/releases

How it works:

  • The -jre-headless package is enough to run Java; a server does not need the compiler or GUI libraries.
  • courseapp is a system user that cannot log in (nologin). If the app has a security hole, an attacker gets only this user's limited rights, not root.
  • The {releases,logs} braces create both folders in one command.

Note: Your exact java -version build string depends on the distribution's update. What matters is the major version (21 here) matching what you tested with.


Copy the JAR to the Server

Copy the JAR from your machine (or CI server) with scp, then move it into a versioned release folder.

# on your machine
scp target/course-server-1.1.0.jar asha@203.0.113.10:/tmp/
# on the server
sudo -u courseapp mkdir -p /opt/course-server/releases/1.1.0
sudo cp /tmp/course-server-1.1.0.jar /opt/course-server/releases/1.1.0/app.jar
sudo chown courseapp:courseapp /opt/course-server/releases/1.1.0/app.jar
sudo -u courseapp ln -sfn /opt/course-server/releases/1.1.0 /opt/course-server/current
ls -l /opt/course-server/current
lrwxrwxrwx 1 courseapp courseapp 34 Nov 18 10:22 /opt/course-server/current -> /opt/course-server/releases/1.1.0

How it works:

  • Each version has its own folder, and the JAR inside is always called app.jar. Scripts only ever refer to current/app.jar.
  • current is a symbolic link. Switching versions means changing one link, and the previous release is still on disk for a fast rollback.
  • 203.0.113.10 is an example address; use your server's IP or host name.

Run the JAR in the Foreground

First run the app by hand to see that it starts.

sudo -u courseapp APP_PORT=8080 APP_ENV=prod java -Xmx256m -jar /opt/course-server/current/app.jar
CourseServer 1.1.0 started on port 8080 (env=prod, java=21)

How it works:

  • sudo -u courseapp runs the JVM as the app user, exactly as it will run later.
  • The process is attached to your terminal. Press Ctrl+C or close the SSH session and the app stops. This is fine for a test, but not for production.

Keep the JAR Running With nohup

nohup starts the process so it survives logout, and & puts it in the background. Output goes to a log file.

cd /opt/course-server
sudo -u courseapp bash -c 'APP_PORT=8080 APP_ENV=prod nohup java -Xmx256m -jar current/app.jar >> logs/app.log 2>&1 & echo $! > app.pid'
cat app.pid
tail -n 1 logs/app.log
curl -s -w "\n" http://localhost:8080/health
805
CourseServer 1.1.0 started on port 8080 (env=prod, java=21)
{"status":"UP","version":"1.1.0","env":"prod","uptimeSeconds":1}

How it works:

  • >> logs/app.log 2>&1 appends both normal output and errors to one log file.
  • $! is the process ID of the last background command. Saving it in app.pid lets you stop exactly this process later with kill $(cat app.pid).
  • Typing this line by hand every time is error-prone, so the next section wraps it in a script.

Externalize Configuration With an Env File

Keep all settings in one file next to the app instead of on the command line.

# /opt/course-server/app.env  (owned by courseapp, mode 600)
APP_PORT=8080
APP_ENV=prod
DB_PASSWORD=change-me
sudo chmod 600 /opt/course-server/app.env
ls -l /opt/course-server/app.env
-rw------- 1 courseapp courseapp 45 Nov 18 10:25 /opt/course-server/app.env

How it works:

  • Mode 600 means only courseapp can read the file, so other users on the server cannot see the password.
  • The same JAR goes to test and production; only app.env differs between the servers.
  • A Spring Boot JAR reads these variables automatically: APP_ENV maps to the property app.env, and SERVER_PORT sets the port. You can also use --spring.config.additional-location=file:/opt/course-server/config/ for a properties file.

A Start/Stop Script for Java JAR Deployment

This script starts, stops, restarts and checks the app. It reads app.env, writes a PID file and gives the JVM time to shut down cleanly.

#!/usr/bin/env bash
# app.sh - start, stop and check the course server
APP_HOME="${APP_HOME:-/opt/course-server}"
JAR="$APP_HOME/current/app.jar"
PID_FILE="$APP_HOME/app.pid"
LOG_FILE="$APP_HOME/logs/app.log"
JAVA_OPTS="${JAVA_OPTS:--Xms128m -Xmx256m}"

# load settings such as APP_PORT and APP_ENV
[ -f "$APP_HOME/app.env" ] && set -a && . "$APP_HOME/app.env" && set +a

is_running() {
    [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null
}

case "$1" in
  start)
    if is_running; then echo "Already running (pid $(cat "$PID_FILE"))"; exit 0; fi
    mkdir -p "$APP_HOME/logs"
    nohup java $JAVA_OPTS -jar "$JAR" >> "$LOG_FILE" 2>&1 &
    echo $! > "$PID_FILE"
    echo "Started (pid $(cat "$PID_FILE"))"
    ;;
  stop)
    if ! is_running; then echo "Not running"; rm -f "$PID_FILE"; exit 0; fi
    PID=$(cat "$PID_FILE")
    kill "$PID"                                  # SIGTERM: shutdown hook runs
    for i in $(seq 1 20); do
      is_running || { rm -f "$PID_FILE"; echo "Stopped"; exit 0; }
      sleep 0.5
    done
    echo "Still running, forcing stop"; kill -9 "$PID"; rm -f "$PID_FILE"
    ;;
  restart)
    "$0" stop
    "$0" start
    ;;
  status)
    if is_running; then echo "Running (pid $(cat "$PID_FILE"))"; else echo "Stopped"; exit 3; fi
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}"; exit 1
    ;;
esac
cd /opt/course-server
sudo -u courseapp ./app.sh start
sudo -u courseapp ./app.sh start
sudo -u courseapp ./app.sh status
ps -o pid,args -p $(cat app.pid)
sudo -u courseapp ./app.sh restart
sudo -u courseapp ./app.sh stop
sudo -u courseapp ./app.sh status; echo "exit code: $?"
cat logs/app.log
Started (pid 805)
Already running (pid 805)
Running (pid 805)
  PID COMMAND
  805 java -Xms128m -Xmx256m -jar /opt/course-server/current/app.jar
Stopped
Started (pid 854)
Stopped
Stopped
exit code: 3
CourseServer 1.1.0 started on port 8080 (env=prod, java=21)
Shutting down...
Stopped.
CourseServer 1.1.0 started on port 8080 (env=prod, java=21)
Shutting down...
Stopped.

How it works:

  • set -a exports every variable loaded from app.env, so the JVM sees them as environment variables.
  • kill -0 sends no signal; it only checks whether the process still exists. That makes is_running safe to call any time.
  • stop sends SIGTERM first, which runs the app's shutdown hook ("Shutting down... Stopped." in the log). Only if the app is still alive after 10 seconds does it use kill -9, which cannot be caught.
  • status returns exit code 3 when stopped, the same convention service managers use, so other scripts can test it.

Tune JVM Options for Production

Pass JVM options through JAVA_OPTS without editing the script.

OptionEffect
-Xms128m -Xmx256mStarting and maximum heap size
-XX:MaxRAMPercentage=75Max heap as a share of available memory (good in containers)
-XX:+ExitOnOutOfMemoryErrorExit instead of limping on after an out-of-memory error
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=logs/Save a heap dump for later analysis
-Duser.timezone=Asia/KolkataFixed time zone, independent of server settings
-Dfile.encoding=UTF-8Explicit text encoding (already the default since JDK 18)
# /opt/course-server/app.env
JAVA_OPTS="-Xmx256m -XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/opt/course-server/logs"
java -XX:+PrintFlagsFinal -version 2>/dev/null | grep -E " ExitOnOutOfMemoryError| HeapDumpOnOutOfMemoryError"
     bool ExitOnOutOfMemoryError                   = false                                     {product} {default}
     bool HeapDumpOnOutOfMemoryError               = false                                  {manageable} {default}

How it works:

  • Because app.sh loads app.env before reading JAVA_OPTS, putting the line in app.env overrides the script's default.
  • -XX:+PrintFlagsFinal lists every JVM flag and its current value. Both flags are false by default, which is why you turn them on explicitly.
  • ExitOnOutOfMemoryError makes the process exit so a script or service manager can restart it, instead of leaving a broken app running. The JVM options lesson covers these flags in more depth.

Note: Ports below 1024, such as 80 and 443, need root rights. Keep the Java app on a high port like 8080 and put a reverse proxy such as Nginx in front of it to handle port 443 and TLS.


Roll Back a JAR Deployment

Because old releases stay in releases/, a rollback is one link change and a restart.

cd /opt/course-server
ls releases
readlink current
sudo -u courseapp ln -sfn /opt/course-server/releases/1.0.0 current
sudo -u courseapp ./app.sh restart
sleep 2
curl -s -w "\n" http://localhost:8080/health
1.0.0
1.1.0
/opt/course-server/releases/1.1.0
Stopped
Started (pid 912)
{"status":"UP","version":"1.0.0","env":"prod","uptimeSeconds":1}

How it works:

  • readlink current shows which release is live before you change anything.
  • After the restart, /health reports version 1.0.0, proving the old release is serving requests.
  • Delete old release folders from time to time, but always keep at least the previous one.

Real-World Example: One-Command JAR Deployment From Your Laptop

This script runs on your machine or in CI. It builds the JAR, uploads it, installs it as a new release on the server, switches current, restarts the app and checks health, rolling back automatically if the new version does not come up. It uses the deploy.sh script from the Java deployment lesson, stored in /opt/course-server on the server.

#!/usr/bin/env bash
# release.sh <version> - build locally and deploy to the server
set -euo pipefail
VERSION="$1"
SERVER="asha@203.0.113.10"
JAR="target/course-server-$VERSION.jar"

echo "==> Building $VERSION"
mvn -q -DskipTests versions:set -DnewVersion="$VERSION" -DgenerateBackupPoms=false
mvn -q -DskipTests clean package
ls -lh "$JAR" | awk '{print "    " $5, $9}'

echo "==> Uploading"
scp -q "$JAR" "$SERVER:/tmp/app-$VERSION.jar"

echo "==> Deploying on server"
ssh "$SERVER" "sudo -u courseapp APP_PORT=8080 /opt/course-server/deploy.sh /tmp/app-$VERSION.jar $VERSION \
               && rm /tmp/app-$VERSION.jar"

echo "==> Done: $VERSION is live"
./release.sh 1.1.0
==> Building 1.1.0
    3.1K target/course-server-1.1.0.jar
==> Uploading
==> Deploying on server
==> 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}
==> Done: 1.1.0 is live

A broken build stops the release and leaves the old version running:

./release.sh 1.2.0
==> Building 1.2.0
    3.1K target/course-server-1.2.0.jar
==> Uploading
==> Deploying on server
==> 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

How it works:

  1. Versioned build. versions:set writes the version into pom.xml, so the JAR name and its manifest Implementation-Version match the release number the health check reports.
  2. Upload then install. The JAR lands in /tmp first and is copied into releases/<version>/app.jar by deploy.sh, running as courseapp, so file ownership is always correct.
  3. Fail fast. set -euo pipefail stops release.sh at the first failing command. When deploy.sh exits with code 1 after a rollback, the ssh command fails, "Done" is never printed, and a CI pipeline marks the job as failed.
  4. No downtime surprises. The old process stops with SIGTERM and finishes open requests before the new one starts. The gap is a second or two; running two instances behind a load balancer removes even that.
  5. Next step. app.sh and nohup do not restart the app after a server reboot or crash. The next lesson, Run as Service, hands the same JAR to systemd so Linux manages it for you.

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 JAR Deployment and get answers drawn from it.

Signed-in readers only.