Sub topic 7
Running the JAR as a systemd service
This chapter covers running the executable JAR on a Linux server under systemd, the init system on most current distributions. It assumes you can build the JAR (earlier chapters), you know how to pass configuration through environment variables, and you have basic shell and sudo skills. Health endpoints and graceful shutdown from earlier chapters matter here, because systemd depends on both.
Why use systemd instead of `java -jar` in a shell
Running java -jar app.jar & in an SSH session works until the session ends, the server reboots, or the process crashes. Nothing restarts it, and nobody records its logs or exit status.
systemd is a service manager. It starts the process at boot, restarts it on failure, captures its output in the journal, and stops it with a signal you can predict. You describe all this in a unit file, a small text file that declares how to run the service.
Prepare the server
Create a dedicated user with no login shell and no home directory. If the application is compromised, the attacker then gets only this account's permissions.
sudo useradd --system --no-create-home --shell /usr/sbin/nologin myapp
sudo mkdir -p /opt/myapp /etc/myapp
sudo cp target/myapp-1.0.0.jar /opt/myapp/app.jar
sudo chown -R root:root /opt/myapp
sudo chmod 644 /opt/myapp/app.jarThe JAR is owned by root and is not writable by myapp. A compromised process therefore cannot replace its own code. If the application must write files, give it a separate directory, such as /var/lib/myapp, and own that directory by myapp.
Install a JDK or JRE of the version you built against, for example with sudo apt install openjdk-21-jre-headless, and confirm the path with readlink -f $(which java).
Store configuration in an environment file
Earlier chapters showed application.properties reading ${DB_URL} and ${DB_PASSWORD}. On a server, systemd supplies those values from an environment file.
sudo tee /etc/myapp/env > /dev/null <<'EOF'
SPRING_PROFILES_ACTIVE=prod
DB_URL=jdbc:postgresql://db.internal:5432/myapp
DB_PASSWORD=change-me
EOF
sudo chown root:myapp /etc/myapp/env
sudo chmod 640 /etc/myapp/envMode 640 with group myapp lets the service read the file while other local users cannot. The file has plain KEY=value lines. systemd does not run it through a shell, so export, quotes handled as in bash, and $VAR expansion do not behave as you might expect. Keep values simple.
Spring Boot's relaxed binding maps SPRING_PROFILES_ACTIVE to spring.profiles.active, so the profile does not need to appear on the command line.
Write the unit file
Save this as /etc/systemd/system/myapp.service:
[Unit]
Description=My Spring Boot app
After=network.target
[Service]
User=myapp
EnvironmentFile=/etc/myapp/env
ExecStart=/usr/bin/java -jar /opt/myapp/app.jar
SuccessExitStatus=143
Restart=on-failure
[Install]
WantedBy=multi-user.targetEach directive does one job:
| Directive | Purpose |
|---|---|
| `After=network.target` | Orders startup after basic networking is configured. It does not wait for the database to be reachable. |
| `User=myapp` | Runs the JVM as the unprivileged account. |
| `EnvironmentFile=` | Loads variables from the file before starting the process. |
| `ExecStart=` | The command. It needs an absolute path to `java`. |
| `SuccessExitStatus=143` | Treats exit code 143 as a success. |
| `Restart=on-failure` | Restarts after a crash or a non-success exit, but not after a clean stop. |
| `WantedBy=multi-user.target` | Starts the service at normal boot when enabled. |
Why exit code 143
When systemd stops a service, it sends SIGTERM. The JVM runs its shutdown hooks and exits with status 128 + 15 = 143. Without SuccessExitStatus=143, systemd records every normal stop as a failure. With Restart=on-failure, that could also cause confusing restart behavior in some setups.
Install, start, and inspect
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
systemctl status myapp
journalctl -u myapp -fdaemon-reload makes systemd re-read unit files. Run it every time you edit the unit. enable registers the service for boot, and --now also starts it immediately.
Spring Boot writes logs to standard output, and systemd sends that output to the journal. You do not need a log file for a basic setup. Useful variations:
journalctl -u myapp --since "10 minutes ago"shows recent logs.journalctl -u myapp -p errshows only error-level lines.systemctl cat myappprints the unit file systemd actually loaded.
Connect to graceful shutdown
The graceful shutdown settings from the earlier chapter are server.shutdown=graceful and a 30 second phase timeout. systemd has its own timer for stopping: TimeoutStopSec, which defaults to 90 seconds on most systems. After that, it sends SIGKILL.
Make sure the systemd timeout is longer than the Spring timeout, or in-flight requests may be killed. Add a margin:
[Service]
TimeoutStopSec=45The sequence on systemctl stop myapp looks like this:
Restart policy and startup failures
Restart=on-failure is a sensible default, but a crash loop can hide a real problem. A bad password in the environment file causes the application to fail on startup, restart, and fail again. Add pacing so the loop does not hammer the database or fill the journal:
[Service]
Restart=on-failure
RestartSec=5
StartLimitIntervalSec=300
StartLimitBurst=5RestartSec waits five seconds between attempts. The two StartLimit directives (which sit in [Unit] on older systemd versions, so check man systemd.unit for your distribution) make systemd give up after five starts in 300 seconds. After that the service enters a failed state until you run systemctl reset-failed myapp and start it again.
Other Restart= values exist. always restarts even after a clean exit, which prevents you from stopping the app with an application-level shutdown. no disables restarts. For most web services on-failure is the right choice.
Start-up readiness
systemd treats the process as started the moment java is launched, which is well before Spring Boot can serve traffic. Deployment scripts that run systemctl restart myapp and then immediately test the application will fail intermittently.
Poll the health endpoint instead. The earlier chapter exposed health through Actuator, so a script can wait for it:
#!/usr/bin/env bash
set -euo pipefail
sudo systemctl restart myapp
for i in $(seq 1 30); do
if curl --silent --fail http://localhost:8080/actuator/health/readiness > /dev/null; then
echo "Application is ready"
exit 0
fi
sleep 2
done
echo "Application did not become ready in 60 seconds" >&2
journalctl -u myapp --no-pager -n 50 >&2
exit 1curl --fail returns a non-zero exit status for HTTP errors such as 503, which is what Actuator returns while the app is starting or shutting down. The script prints recent logs on failure so the cause is visible in the CI output.
Hardening options
systemd can restrict what the process may do, which limits damage from a vulnerability. These directives are low-risk for a typical web service:
[Service]
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/myappNoNewPrivilegesstops the process and its children from gaining privileges, for example through setuid binaries.PrivateTmpgives the service its own/tmp.ProtectSystem=strictmounts the whole file system read-only for the service, except the paths inReadWritePaths.ProtectHomehides user home directories.
Add them one at a time and restart after each. ProtectSystem=strict is the one most likely to break something. For example, an application that writes to a log directory or uploads folder will fail with a permission error until you list that directory in ReadWritePaths. Note also that ReadWritePaths fails to start the unit if the directory does not exist.
Deploying a new version
A simple release on one server has four steps:
- Copy the new JAR to a temporary name, such as
/opt/myapp/app.jar.new. - Move it over
app.jarwithmv, which is atomic on the same file system. - Run
systemctl restart myapp. - Wait for the readiness check described above.
Keep the previous JAR, for example as app.jar.prev, so you can roll back by swapping the names and restarting. A restart on a single server means a short outage, even with graceful shutdown, because the new process takes time to start. Zero-downtime releases need at least two instances behind a load balancer, which the Kubernetes chapter covers.
Common errors
| Symptom | Likely cause |
|---|---|
| `status=203/EXEC` | `ExecStart` path is wrong, for example `java` is not at `/usr/bin/java`. |
| `status=200/CHDIR` or `217/USER` | The working directory or `User=` account does not exist. |
| Service flaps between `activating` and `failed` | Application fails at startup. Read `journalctl -u myapp`. |
| Placeholders such as `${DB_URL}` are unresolved | The environment file is not loaded, has a typo, or has wrong permissions. |
| Edits to the unit have no effect | You forgot `systemctl daemon-reload`. |
| Requests are cut during a restart | `TimeoutStopSec` is shorter than the Spring shutdown phase. |
Exercise
A deployment script runs systemctl restart myapp and immediately calls curl http://localhost:8080/api/orders. The call sometimes fails with "connection refused", although systemctl status shows the service as active. Why does this happen, and how do you fix the script?
Show answer
systemd considers the service started as soon as the java process is launched, which happens before Spring Boot finishes starting and opens its port. The script must wait for readiness, for example by polling /actuator/health/readiness with curl --fail in a loop with a timeout, and failing the deployment if the application does not become ready.
Exercise
Your Spring Boot configuration sets spring.lifecycle.timeout-per-shutdown-phase=60s, but the unit file does not set TimeoutStopSec, and you run on a system where the default is 30 seconds. What goes wrong on systemctl stop, and what value would you choose?
Show answer
systemd sends SIGKILL after 30 seconds, so requests that need more time are dropped and the JVM does not exit with code 143. Set TimeoutStopSec above the Spring timeout, for example 75, so the graceful phase can finish before systemd forces the stop.