Run Java as a Service

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

To run Java as a service means letting the operating system start your application at boot, restart it when it crashes and collect its logs, without anyone logged in. On Linux the standard tool for this is systemd, which manages almost every background program on Ubuntu, Debian, Fedora and RHEL. A small text file called a unit file is all you need.

This lesson turns the CourseServer JAR from Java JAR Deployment into a systemd service, then does the same for Tomcat from Java WAR Deployment. All commands were tested on Ubuntu 24.04 with JDK 21.


Why Run Java as a Service Instead of nohup

The app.sh script with nohup from the previous lessons keeps the app running after logout, but it has limits.

Neednohup + scriptsystemd service
Start after a rebootNoYes (enable)
Restart after a crashNoYes (Restart=on-failure)
Stop cleanly with SIGTERMYour script must do itBuilt in
Collect stdout/stderrManual log fileJournal (journalctl)
Run as a non-root usersudo -u every timeUser= line
Limit memory, files, permissionsNot possibleBuilt-in options

How it works:

  • systemd starts as process 1 when Linux boots and keeps track of every service it starts, including its child processes.
  • Because systemd itself watches the process, it knows the moment your JVM dies and can start it again.

A Minimal systemd Unit File for a Java App

A unit file has three sections. [Unit] describes the service, [Service] says how to run it, and [Install] says when to start it at boot.

# /etc/systemd/system/course-server.service
[Unit]
Description=Course Server (Java)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=courseapp
Group=courseapp
WorkingDirectory=/opt/course-server
EnvironmentFile=/opt/course-server/app.env
ExecStart=/usr/bin/java -Xms128m -Xmx256m -jar /opt/course-server/current/app.jar
SuccessExitStatus=143
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Key Unit File Settings

SettingMeaning
After=network-online.targetStart only after the network is up
Type=simpleThe process in ExecStart is the service; it must not fork into the background
User= / Group=Run the JVM as this account, never root
EnvironmentFile=Load KEY=value lines as environment variables
ExecStart=Full command; the program needs an absolute path
SuccessExitStatus=143Treat exit code 143 (SIGTERM) as a normal stop
Restart=on-failureRestart on crashes and non-zero exits, not on a clean stop
RestartSec=5Wait 5 seconds before restarting
WantedBy=multi-user.targetStart at normal boot when the service is enabled

How it works:

  • Do not use nohup or & in ExecStart. systemd already runs the process in the background and would lose track of it if it forked.
  • When a JVM receives SIGTERM it runs its shutdown hooks and exits with code 143 (128 + signal 15). Without SuccessExitStatus=143, every normal stop would be shown as failed.
  • EnvironmentFile reads the same app.env file used by app.sh, so APP_PORT and APP_ENV keep working.

Start, Enable and Check the Java Service

After creating or editing a unit file, tell systemd to re-read it, then enable and start the service.

sudo systemctl daemon-reload
sudo systemctl enable --now course-server
systemctl status course-server --no-pager
Created symlink /etc/systemd/system/multi-user.target.wants/course-server.service → /etc/systemd/system/course-server.service.
● course-server.service - Course Server (Java)
     Loaded: loaded (/etc/systemd/system/course-server.service; enabled; preset: enabled)
     Active: active (running) since Wed 2026-11-18 11:05:12 IST; 2s ago
   Main PID: 1342 (java)
      Tasks: 17 (limit: 4551)
     Memory: 41.6M (peak: 41.9M)
        CPU: 512ms
     CGroup: /system.slice/course-server.service
             └─1342 /usr/bin/java -Xms128m -Xmx256m -jar /opt/course-server/current/app.jar

Nov 18 11:05:12 web01 systemd[1]: Started course-server.service - Course Server (Java).
Nov 18 11:05:12 web01 java[1342]: CourseServer 1.1.0 started on port 8080 (env=prod, java=21)
curl -s -w "\n" http://localhost:8080/health
{"status":"UP","version":"1.1.0","env":"prod","uptimeSeconds":4}

How it works:

  • enable creates a link so the service starts at boot. --now also starts it immediately.
  • Loaded: ... enabled confirms boot start. Active: active (running) confirms the JVM is alive.
  • The last lines of status show the newest log output, including the app's own startup message.

Everyday systemctl Commands

CommandEffect
sudo systemctl start course-serverStart now
sudo systemctl stop course-serverSend SIGTERM and wait for the JVM to exit
sudo systemctl restart course-serverStop, then start
sudo systemctl enable course-serverStart automatically at boot
sudo systemctl disable course-serverDo not start at boot
systemctl is-active course-serverPrint active or inactive (good for scripts)
sudo systemctl daemon-reloadRe-read unit files after editing them

Read Java Service Logs With journalctl

Everything the JVM prints to stdout and stderr goes to the systemd journal. You do not need a separate log file.

sudo systemctl stop course-server
journalctl -u course-server --since "10 min ago" --no-pager
Nov 18 11:05:12 web01 systemd[1]: Started course-server.service - Course Server (Java).
Nov 18 11:05:12 web01 java[1342]: CourseServer 1.1.0 started on port 8080 (env=prod, java=21)
Nov 18 11:09:40 web01 systemd[1]: Stopping course-server.service - Course Server (Java)...
Nov 18 11:09:40 web01 java[1342]: Shutting down...
Nov 18 11:09:42 web01 java[1342]: Stopped.
Nov 18 11:09:42 web01 systemd[1]: course-server.service: Deactivated successfully.
Nov 18 11:09:42 web01 systemd[1]: Stopped course-server.service - Course Server (Java).
OptionExampleShows
-u <unit>-u course-serverOnly this service
-fjournalctl -u course-server -fNew lines live, like tail -f
-n <N>-n 50Last N lines
--since / --until--since todayA time range
-p err-p errOnly error-level messages
-b-bSince the last boot

How it works:

  • Shutting down... and Stopped. come from the app's shutdown hook, proving systemctl stop sent SIGTERM and the JVM closed cleanly.
  • Deactivated successfully appears because exit code 143 is listed in SuccessExitStatus.

Restart a Java Service Automatically After a Crash

Test the restart policy by killing the JVM the hard way, as a crash or out-of-memory kill would.

sudo systemctl start course-server
sudo kill -9 "$(systemctl show -p MainPID --value course-server)"
sleep 6
journalctl -u course-server -n 5 --no-pager
systemctl show -p NRestarts course-server
Nov 18 11:12:03 web01 systemd[1]: course-server.service: Main process exited, code=killed, status=9/KILL
Nov 18 11:12:03 web01 systemd[1]: course-server.service: Failed with result 'signal'.
Nov 18 11:12:08 web01 systemd[1]: course-server.service: Scheduled restart job, restart counter is at 1.
Nov 18 11:12:08 web01 systemd[1]: Started course-server.service - Course Server (Java).
Nov 18 11:12:09 web01 java[1588]: CourseServer 1.1.0 started on port 8080 (env=prod, java=21)
NRestarts=1

How it works:

  • kill -9 cannot be caught, so no shutdown hook runs. systemd sees status=9/KILL and treats it as a failure.
  • After RestartSec=5 seconds it starts a new JVM (new PID 1588). NRestarts counts how often this happened.
  • Add -XX:+ExitOnOutOfMemoryError to ExecStart so an out-of-memory error ends the JVM and triggers this same restart instead of leaving a half-working app.

Stop a Restart Loop

If the app crashes on every start (for example a bad config value), endless restarts only fill the logs. Limit them in [Unit]:

[Unit]
StartLimitIntervalSec=60
StartLimitBurst=3
Nov 18 11:20:31 web01 systemd[1]: course-server.service: Start request repeated too quickly.
Nov 18 11:20:31 web01 systemd[1]: course-server.service: Failed with result 'exit-code'.

How it works:

  • With these values, systemd gives up after 3 failed starts within 60 seconds and marks the service failed.
  • Fix the problem, then run sudo systemctl reset-failed course-server and start it again.

Pass JVM Options Through the Environment File

Hard-coding -Xmx in the unit file means editing it for every change. Use a variable from app.env instead.

# /opt/course-server/app.env
APP_PORT=8080
APP_ENV=prod
JAVA_OPTS=-Xms128m -Xmx256m -XX:+ExitOnOutOfMemoryError
# in [Service]
ExecStart=/usr/bin/java $JAVA_OPTS -jar /opt/course-server/current/app.jar
sudo systemctl daemon-reload && sudo systemctl restart course-server
ps -o args= -p "$(systemctl show -p MainPID --value course-server)"
/usr/bin/java -Xms128m -Xmx256m -XX:+ExitOnOutOfMemoryError -jar /opt/course-server/current/app.jar

How it works:

  • In ExecStart, $JAVA_OPTS (without braces) is split on spaces into separate arguments. ${JAVA_OPTS} would pass the whole value as one argument, which the JVM would reject.
  • systemd does not use a shell, so do not write quotes around the value in app.env unless the quotes should become part of it.

Harden the Java Service With Sandboxing

systemd can lock the service down so a compromised app cannot touch the rest of the server. Add these lines to [Service]:

NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/course-server/logs
LimitNOFILE=65536
OptionEffect
NoNewPrivileges=trueThe process can never gain more rights (no sudo, no setuid)
PrivateTmp=trueThe app gets its own empty /tmp
ProtectSystem=strictThe whole file system is read-only for the service
ReadWritePaths=Exceptions to strict: folders the app may write
ProtectHome=true/home, /root and /run/user are hidden
LimitNOFILE=65536Raise the open-file limit for many connections
sudo systemctl daemon-reload && sudo systemctl restart course-server
systemctl show -p ProtectSystem -p NoNewPrivileges -p LimitNOFILE course-server
grep "Max open files" /proc/"$(systemctl show -p MainPID --value course-server)"/limits
ProtectSystem=strict
NoNewPrivileges=yes
LimitNOFILE=65536
Max open files            65536                65536                files

How it works:

  • systemctl show prints the settings systemd actually applied, and /proc/<pid>/limits confirms the running JVM got the higher file limit.
  • The protections apply only to processes started by the service. If the app tries to write outside ReadWritePaths, Java throws java.nio.file.FileSystemException: ... Read-only file system.
  • ReadWritePaths must list every folder the app writes to, such as log or upload folders.

Run Tomcat as a systemd Service

The same pattern works for Tomcat. Run catalina.sh run, which keeps Tomcat in the foreground, so Type=simple still fits.

# /etc/systemd/system/tomcat.service
[Unit]
Description=Apache Tomcat 11
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=tomcat
Group=tomcat
Environment=CATALINA_HOME=/opt/tomcat CATALINA_BASE=/opt/tomcat
ExecStart=/opt/tomcat/bin/catalina.sh run
SuccessExitStatus=143
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
sudo -u tomcat /opt/tomcat/bin/shutdown.sh   # stop the copy started by hand
sudo systemctl daemon-reload
sudo systemctl enable --now tomcat
systemctl is-active tomcat
curl -s "http://localhost:8080/student-portal/hello?name=Asha"
active
Hello, Asha!

How it works:

  • catalina.sh run still reads bin/setenv.sh, so the heap settings from the WAR lesson apply unchanged.
  • startup.sh would start Tomcat in the background and return immediately, which needs Type=forking and a PID file. catalina.sh run avoids that complexity.
  • Tomcat's output now goes to the journal: read it with journalctl -u tomcat -f.

Real-World Example: Deploy and Run Java as a Service With Health Checks

This version of the deployment script uses systemd instead of app.sh. A narrow sudoers rule lets the deploy user restart only this one service, and on failure the script prints the journal so the CI log shows why.

# /etc/sudoers.d/course-server  (edit with: sudo visudo -f /etc/sudoers.d/course-server)
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart course-server, /usr/bin/systemctl is-active course-server
#!/usr/bin/env bash
# deploy-service.sh <jar-file> <version>
set -euo pipefail
APP_HOME=/opt/course-server
SERVICE=course-server
JAR_FILE="$1"
VERSION="$2"

restart_and_check() {
  sudo systemctl restart "$SERVICE"
  for i in $(seq 1 20); do
    if curl -fs http://localhost:8080/health > /dev/null; then
      echo "==> Healthy: $(curl -s http://localhost:8080/health)"
      return 0
    fi
    sleep 0.5
  done
  return 1
}

echo "==> Installing $VERSION"
mkdir -p "$APP_HOME/releases/$VERSION"
cp "$JAR_FILE" "$APP_HOME/releases/$VERSION/app.jar"
PREVIOUS=$(readlink "$APP_HOME/current" || true)
ln -sfn "$APP_HOME/releases/$VERSION" "$APP_HOME/current"

if restart_and_check; then
  echo "==> $VERSION is live ($(sudo systemctl is-active "$SERVICE"))"
  exit 0
fi

echo "==> $VERSION failed, last log lines:"
journalctl -u "$SERVICE" -n 5 --no-pager -o cat
ln -sfn "$PREVIOUS" "$APP_HOME/current"
restart_and_check && echo "==> Rolled back to $(basename "$PREVIOUS")"
exit 1
sudo -u deploy ./deploy-service.sh /tmp/course-server-1.2.0.jar 1.2.0; echo "exit=$?"
==> Installing 1.2.0
==> 1.2.0 failed, last log lines:
Stopped course-server.service - Course Server (Java).
Started course-server.service - Course Server (Java).
Error: Could not find or load main class com.gocourse.app.CourseServerr
Caused by: java.lang.ClassNotFoundException: com.gocourse.app.CourseServerr
course-server.service: Main process exited, code=exited, status=1/FAILURE
==> Healthy: {"status":"UP","version":"1.1.0","env":"prod","uptimeSeconds":0}
==> Rolled back to 1.1.0
exit=1

How it works:

  1. Least privilege. The deploy user owns the release folders but may run only two exact systemctl commands as root. It cannot stop other services or edit the unit file. (Give deploy write access to /opt/course-server, for example by adding it to the courseapp group.)
  2. systemd does the process work. No PID files, no nohup, no kill loops. restart sends SIGTERM, waits for the shutdown hook, and starts the JVM again as courseapp.
  3. Logs explain failures. journalctl -o cat prints only the messages, so the CI output shows the real cause: a typo in the Main-Class of build 1.2.0.
  4. Rollback. The current link goes back to 1.1.0 and the health check confirms it. Because the unit has Restart=on-failure, a crash later in production is also handled without anyone logged in.
  5. Next step. A container image packages the runtime, the JAR and this start command together. The next lesson, Dockerize a Java Application, shows how.

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 Run Java as a Service and get answers drawn from it.

Signed-in readers only.