34

I want to start and stop my jar file as follows

service myService start

service myService stop

my current jar file running as follows

cd /home/alex/IdeaProjects/myService
java -jar target/myService-SNAPSHOT-1.jar server config.yml

What should I do?

user3086014
  • 4,241
  • 5
  • 27
  • 56
Alex Mathew
  • 3,925
  • 5
  • 21
  • 25
  • Implement a wrapper service. A little search will show up some 3rd party implementation you could use. – Henry Feb 04 '14 at 07:22
  • 1
    Dupe http://stackoverflow.com/questions/11203483/run-a-java-application-as-a-service-on-linux – giorgio79 Apr 11 '16 at 09:25

3 Answers3

32

You need a Service Wrapper to run the Jar file.

There are examples and instructions for init.d here. or for systemd (ubuntu 16+) here

PbxMan
  • 7,525
  • 1
  • 36
  • 40
  • Just an info for people who are on Ubuntu 16+. This doesn't work with Ubuntu 16+. You will get 'Failed to start MyService.service: Unit MyService.service not found' – Dino Nov 14 '17 at 12:59
  • systemd version works awesome :D – SubjectX Mar 22 '18 at 08:20
6

I prefer a light weight, free, bash script rather than a more elaborate system that requires licensing.

http://gustavostraube.wordpress.com/2009/11/05/writing-an-init-script-for-a-java-application/

Running jar as a Linux service - init.d script gets stuck starting app

https://askubuntu.com/questions/99232/how-to-make-a-jar-file-run-on-startup-and-when-you-log-out

Community
  • 1
  • 1
user2684301
  • 2,550
  • 1
  • 24
  • 33
3

If you want to try the DIY way, you can place a startup script in your /etc/init.d directory as said here.

http://www.ghacks.net/2009/04/04/get-to-know-linux-the-etcinitd-directory/

However, to implement a clean yourScript stop command, I would recommend that you split your functionality into a launcher and a daemon, and make your launcher able to start or communicate with your existing daemon in order to send orders to it. Then your startup script would only invoke your launcher, which in its turn would start a new daemon, or send orders to the existing one.

Jorge_B
  • 9,712
  • 2
  • 17
  • 22
  • Request: Could you plz post a small example of launcher and daemon(for this particular case) Or add link to some effective tutorial. Thanks. – Alex Mathew Feb 04 '14 at 08:52
  • I am afraid I have nothing at hand. Your best shot is to leave a port open in your service for administration purposes just as application servers do, and then write a simple 30-40 lines program (your launcher) that sends orders to that port. Then your service would have a thread listening on that port, processing the restart or stop orders – Jorge_B Feb 04 '14 at 08:55
  • Sime time ago I was solving similar task I documented https://jaksky.wordpress.com/2013/11/03/java-application-as-a-linux-service/ – jaksky Feb 14 '16 at 09:50