Tim Cooke

Add a Linux service on Ubuntu

7th August 2020

I have an application that I need to run on a Linux server, but I need it to be able to recover from a system restart or a process failure, and start up again automatically. The best way I know to achieve that is to configure the application as a system service, and since I'm using Ubuntu then systemd is what I need to work with.

In order to test this out I'm going to be using a jar file, hello.jar, that runs a small REST api service. It is started like this:

$ java -jar hello.jar

The API has a single GET endpoint:

$ curl localhost:8080/hello
Hello, World!

But as soon as the process is stopped, which could happen because the server restarted, or the process died or was killed for some reason, then there is no recovery:

$ curl localhost:8080/hello
curl: (7) Failed to connect to localhost port 8080: Connection refused

Oh dear.

Let's add the application as a process. First create a file /lib/systemd/system/hello.service.

[Unit]
Description=Hello REST api

[Service]
Restart=always
RestartSec=1
User=tim
ExecStart=java -jar /home/tim/Development/deployment/hello.jar

[Install]
WantedBy=multi-user.target

Once that file is saved then the service is created but not started

$ service hello status
● hello.service - Hello REST api
     Loaded: loaded (/lib/systemd/system/hello.service; disabled; vendor preset>
     Active: inactive (dead)

Now to start the service

$ sudo service hello start
$ service hello status
● hello.service - Hello REST api
     Loaded: loaded (/lib/systemd/system/hello.service; disabled; vendor preset: enabled)
     Active: active (running) since Fri 2020-08-07 12:45:45 BST; 5s ago
   Main PID: 4973 (java)
      Tasks: 40 (limit: 18808)
     Memory: 263.4M
     CGroup: /system.slice/hello.service
             └─4973 /usr/bin/java -jar /home/tim/Development/deployment/hello.jar

This is good, but notice the line loaded (/lib/systemd/system/hello.service; disabled; vendor preset: enabled), particularly where it says disabled which means it will not start automatically. It needs to be enabled for that to happen.

$ sudo systemctl enable hello
Created symlink /etc/systemd/system/multi-user.target.wants/hello.service → /lib/systemd/system/hello.service.

Now the status report says it's enabled and will now be automatically started after a system reboot.

$ service hello status
● hello.service - Hello REST api
     Loaded: loaded (/lib/systemd/system/hello.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2020-08-07 12:45:45 BST; 10min ago
   Main PID: 4973 (java)
      Tasks: 38 (limit: 18808)
     Memory: 264.0M
     CGroup: /system.slice/hello.service
             └─4973 /usr/bin/java -jar /home/tim/Development/deployment/hello.jar