Run Java as a Service
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.
| Need | nohup + script | systemd service |
|---|---|---|
| Start after a reboot | No | Yes (enable) |
| Restart after a crash | No | Yes (Restart=on-failure) |
| Stop cleanly with SIGTERM | Your script must do it | Built in |
| Collect stdout/stderr | Manual log file | Journal (journalctl) |
| Run as a non-root user | sudo -u every time | User= line |
| Limit memory, files, permissions | Not possible | Built-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
| Setting | Meaning |
|---|---|
After=network-online.target | Start only after the network is up |
Type=simple | The 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=143 | Treat exit code 143 (SIGTERM) as a normal stop |
Restart=on-failure | Restart on crashes and non-zero exits, not on a clean stop |
RestartSec=5 | Wait 5 seconds before restarting |
WantedBy=multi-user.target | Start at normal boot when the service is enabled |
How it works:
- Do not use
nohupor&inExecStart. 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 asfailed. EnvironmentFilereads the sameapp.envfile used byapp.sh, soAPP_PORTandAPP_ENVkeep 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:
enablecreates a link so the service starts at boot.--nowalso starts it immediately.Loaded: ... enabledconfirms boot start.Active: active (running)confirms the JVM is alive.- The last lines of
statusshow the newest log output, including the app's own startup message.
Everyday systemctl Commands
| Command | Effect |
|---|---|
sudo systemctl start course-server | Start now |
sudo systemctl stop course-server | Send SIGTERM and wait for the JVM to exit |
sudo systemctl restart course-server | Stop, then start |
sudo systemctl enable course-server | Start automatically at boot |
sudo systemctl disable course-server | Do not start at boot |
systemctl is-active course-server | Print active or inactive (good for scripts) |
sudo systemctl daemon-reload | Re-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).
| Option | Example | Shows |
|---|---|---|
-u <unit> | -u course-server | Only this service |
-f | journalctl -u course-server -f | New lines live, like tail -f |
-n <N> | -n 50 | Last N lines |
--since / --until | --since today | A time range |
-p err | -p err | Only error-level messages |
-b | -b | Since the last boot |
How it works:
Shutting down...andStopped.come from the app's shutdown hook, provingsystemctl stopsent SIGTERM and the JVM closed cleanly.Deactivated successfullyappears because exit code 143 is listed inSuccessExitStatus.
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 -9cannot be caught, so no shutdown hook runs. systemd seesstatus=9/KILLand treats it as a failure.- After
RestartSec=5seconds it starts a new JVM (new PID 1588).NRestartscounts how often this happened. - Add
-XX:+ExitOnOutOfMemoryErrortoExecStartso 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-serverand 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.envunless 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
| Option | Effect |
|---|---|
NoNewPrivileges=true | The process can never gain more rights (no sudo, no setuid) |
PrivateTmp=true | The app gets its own empty /tmp |
ProtectSystem=strict | The 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=65536 | Raise 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 showprints the settings systemd actually applied, and/proc/<pid>/limitsconfirms 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 throwsjava.nio.file.FileSystemException: ... Read-only file system. ReadWritePathsmust 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 runstill readsbin/setenv.sh, so the heap settings from the WAR lesson apply unchanged.startup.shwould start Tomcat in the background and return immediately, which needsType=forkingand a PID file.catalina.sh runavoids 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:
- Least privilege. The
deployuser owns the release folders but may run only two exactsystemctlcommands as root. It cannot stop other services or edit the unit file. (Givedeploywrite access to/opt/course-server, for example by adding it to thecourseappgroup.) - systemd does the process work. No PID files, no
nohup, nokillloops.restartsends SIGTERM, waits for the shutdown hook, and starts the JVM again ascourseapp. - Logs explain failures.
journalctl -o catprints only the messages, so the CI output shows the real cause: a typo in theMain-Classof build 1.2.0. - Rollback. The
currentlink goes back to 1.1.0 and the health check confirms it. Because the unit hasRestart=on-failure, a crash later in production is also handled without anyone logged in. - Next step. A container image packages the runtime, the JAR and this start command together. The next lesson, Dockerize a Java Application, shows how.