Running “java -jar YOURjarfile.jar” will of course start a jar on your linux machine, but it will stop running once you disconnect your ssh session for instance. So you do need to run your jar file in the background.
Pierre Janineh described a way to achieve this goal:
%[https://medium.com/programming-with-pierre/start-a-java-service-from-jar-on-an-ubuntu-instance-40dff8acc4a5]
Another approach is obviously to run your jar “as a service” via systemd. If you ensure that this service will auto restart in case of a failure or after reboot, you Java application will again restart magically and automatically.
For those interested in running jar files as a Windows Service Matt Passarelli has you covered with his article:
%[https://medium.com/@mattvpassarelli/how-to-run-a-jar-as-a-windows-service-with-nssm-d938e9a7378]
On Linux, some “wrapper” tools can make your life even easier. pm2 is one option:
%[https://pm2.keymetrics.io]
I like to use “supervisord” on Linux.
Both tools, supervisord and pm2, offer monitoring functionality and are relatively easy to install, supervisord is very straight forward. Let’s assume your jar-file for your app named yourAppName, got uploaded to /var/yourFolder/yourFileName.jar:
Installation (test on Ubuntu 22.04)
sudo apt-get install -y supervisor
Creating your configuration file
Instead of vi, you can of course any editor of your choice, nano etc.
sudo vi /etc/supervisor/conf.d/yourAppName.conf
Put the following content into it, but please don’t forget to change the variables to your needs:
[program:yourAppName]
command=/usr/bin/java -jar /var/yourFolder/yourFileName.jar
directory=/var/yourFolder/
autorestart=true
autostart=true
stopasgroup=true
user=yourUser
; Log files
stdout_logfile=pathToYourLogFile
stdout_logfile_maxbytes=50MB
stdout_logile_backups=10
stderr_logfile=pathToYourErrorLogFile
stderr_logfile_maxbytes=50MB
stderr_logfile_backups=10
After saving that file, please stop and start supervisord first:
sudo systemctl stop supervisor
sudo systemctl start supervisor
so that your new configuration will be loaded as well. Next, you need to start your new service.
sudo supervisorctl start yourAppName
That’s it. If your new service yourAppName will start w/o any errors you can now be sure that the service will restart upon errors or for instance after a reboot. Please check if everything is working as expected.
Last but not least: Please check the supervisord homepage to read more about the many other options you can configure in your configuration file too.