How do you run a Spring Boot JAR as a Linux service so it survives reboots?
BeginnerHands-onJava builds (Maven, Gradle, JAR, WAR)
Answer
Short answer
Create a systemd unit file that runs java -jar, enable it, and start it. systemd then starts the app on boot, restarts it if it crashes, and collects its logs in journald.
Steps
sudo useradd -r -s /usr/sbin/nologin orders # dedicated user, no login shell
sudo mkdir -p /opt/orders && sudo cp orders-1.4.0.jar /opt/orders/orders.jar
sudo chown -R orders:orders /opt/orders
# /etc/systemd/system/orders.service
[Unit]
Description=Orders API
After=network.target
[Service]
User=orders
WorkingDirectory=/opt/orders
Environment=SPRING_PROFILES_ACTIVE=prod
EnvironmentFile=-/etc/orders/orders.env # secrets file, chmod 600
ExecStart=/usr/bin/java -Xms512m -Xmx1g -jar /opt/orders/orders.jar
SuccessExitStatus=143
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now orders
systemctl status orders
journalctl -u orders -f
Notes
SuccessExitStatus=143— Java exits with 143 when stopped by SIGTERM; this tells systemd that's a normal stop.- Never run the app as root.
What to say in the interview
"I create a dedicated non-root user, a systemd unit with ExecStart running java -jar, Restart=on-failure and environment from a protected env file, then enable it. Logs go to journald. In containerised setups Kubernetes replaces this role."
All Build Tools (Java, Node.js, Python, .NET) questions Roadmap: Java apps: Maven, Gradle, JAR & WAR
More on Java builds (Maven, Gradle, JAR, WAR)
What is pom.xml and what is it used for?BeginnerHow do you build and run a Java project with Maven?BeginnerWhat is the difference between a JAR and a WAR file?BeginnerWhat is Gradle and how is it different from Maven?BeginnerHow do you configure a Spring Boot application for different environments?BeginnerA Maven build fails in the pipeline with "Could not resolve dependencies". How do you fix it?Intermediate