Video in progress

How do you run a Spring Boot jar as a systemd service on a plain Linux VM, and what do you watch in the unit file?

I write the unit to run under a dedicated user: a direct java -jar in ExecStart, Restart=on-failure, SuccessExitStatus=143 and LimitNOFILE. Logs go to journald, and settings and passwords come through EnvironmentFile.

📖 Answer

# /etc/systemd/system/shop-api.service
[Unit]
Description=Shop API
After=network-online.target
Wants=network-online.target

[Service]
User=shop
Group=shop
WorkingDirectory=/opt/shop-api
EnvironmentFile=/etc/shop-api/env
ExecStart=/usr/bin/java -Xmx1g -jar /opt/shop-api/app.jar
SuccessExitStatus=143
Restart=on-failure
RestartSec=5
TimeoutStopSec=40
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now shop-api
journalctl -u shop-api -f

The subtle points:

  • SuccessExitStatus=143. When the JVM stops on SIGTERM, it exits with code 143 (128+15). Without this, every ordinary systemctl stop is marked "failed" and the alerts get noisy.
  • TimeoutStopSec: after SIGTERM, systemd waits this long, then sends SIGKILL. The default is 90 seconds; keep it larger than Spring's timeout-per-shutdown-phase.
  • LimitNOFILE: systemd services do not read /etc/security/limits.conf, which is for login sessions. The limit is set only in the unit.
  • Give EnvironmentFile permissions 600, owned by root. If you put the password on the ExecStart line as --spring.datasource.password=..., everyone can see it in ps aux.
  • On a VM, MaxRAMPercentage is computed from the whole machine's RAM. If something else runs on the machine, it is better to set an explicit -Xmx.

Deploying is simple: you put the new jar down as app-1.5.0.jar, swap the app.jar symlink, and run systemctl restart. Rollback is switching the symlink back. On a single VM this causes downtime, so you need two VMs behind a load balancer, updated one at a time.