Skip to content

Instantly share code, notes, and snippets.

@brandonjyee
Last active February 2, 2024 15:05
Show Gist options
  • Save brandonjyee/bc0cdc005b7115943549ecfdb0a063ed to your computer and use it in GitHub Desktop.
Save brandonjyee/bc0cdc005b7115943549ecfdb0a063ed to your computer and use it in GitHub Desktop.
Deploying Spring Boot app as a Linux service
This method uses the modern systemd way to run a Java JAR (i.e. a Spring Boot app) as a daemon as opposed to using the older method of using init.d (SystemV). Using the "&" symbol to run the process in the background isn't sufficient b/c the process will be shut down when the terminal closes (or when you exit your SSH session if remoting in to the machine). Using the "nohup" command is another option, but that is like the "poor man's way" of running a service: doesn't restart on machine reboot; program ignores interrupts, quit signals, and hangups. For more info see: https://stackoverflow.com/questions/958249/whats-the-difference-between-nohup-and-a-daemon .
Anyways, to create a Linux daemon the systemd way:
Create a service file in /etc/systemd/system. Let's call it javaservice.service. Let the contents be:
[Unit]
Description=My Java Service
[Service]
User=someuser
# The configuration file application.properties should be here:
WorkingDirectory=/home/myuser/my-apps
ExecStart=/usr/bin/java -Xmx256m -jar application.jar --server.port=9900
SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload <== notifies systemd of the new service file
sudo systemctl enable javaservice.service <== enable it so it runs on boot
// javaservice.service will be added to the dir /etc/systemd/system/multi-user.target.wants. This dir indicates what services to start on boot
sudo systemctl start javaservice
sudo systemctl status javaservice <== check that the service is running fine
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment