Spring Boot application as a Service
In this tutorial we are going to learn about Spring Boot application as a Service.
The following works for springboot 1.3 and above:
As init.d service
The executable jar has the usual start, stop, restart, and status commands. It will also set up a PID file in the usual /var/run directory and logging in the usual /var/log directory by default.
You just need to symlink your jar into /etc/init.d like so
sudo link -s /var/myapp/myapp.jar /etc/init.d/myapp
sudo ln -s ~/myproject/build/libs/myapp-1.0.jar /etc/init.d/myapp_servicename
After that you can do the usual
Then setup a link in whichever runlevel you want the app to start/stop in on boot if so desired.
As a systemd service
To run a Spring Boot application installed in var/myapp you can add the following script in /etc/systemd/system/myapp.service:
[Unit] Description=myapp After=syslog.target [Service] ExecStart=/var/myapp/myapp.jar [Install] WantedBy=multi-user.target
In case you are using this method, do not forget to make the jar file itself executable (with chmod +x) otherwise it will fail with error “Permission denied”.
Let’s assume you are using systemd (which any modern distro nowadays does):
Firstly, create a service file in /etc/systemd/system named e.g. javaservice.service with this content:
[Unit] Description=Java Service [Service] User=nobody # The configuration file application.properties should be here: WorkingDirectory=/data ExecStart=/usr/bin/java -Xmx256m -jar application.jar --server.port=8081 SuccessExitStatus=143 TimeoutStopSec=10 Restart=on-failure RestartSec=5 [Install] WantedBy=multi-user.target
Secondly, notify systemd of the new service file:
and enable it, so it runs on boot:
systemctl enable javaservice.service
Eventually, you can use the following commands to start/stop your new service:
systemctl start javaservice systemctl stop javaservice systemctl restart javaservice systemctl status javaservice
Provided you are using systemd, this is the most non-intrusive and clean way to set up a Java application as system-service.
What I like especially about this solution is the fact that you don’t need to install and configure any other software. The shipped systemd does all the work for you, and your service behaves like any other system service. I use it in production for a while now, on different distros, and it just works as you would expect.
Another plus is that, by using /usr/bin/java, you can easily add jvm paramters such as -Xmx256m.