Linux Server

How to run java jar application with systemd on Linux as service

On Linux systems, we can run the java jar by using the java -jar application.jar command. But to run the application on Linux startup and as a service, we need to use one of the options systemd.

Considering the application jar file located at /opt/ directory and we will be using a logged-in user ($USER) to run the application with systemd. You can also create a system user for the same purpose as well.

Change application read/write permission for a logged-in user in our jar directory.

sudo chown -R $USER:$USER /opt

Create a service file

sudo vi /etc/systemd/system/blog.service

It will have the following content:

[Unit]
Description=Blog service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/

ExecStart=/usr/bin/java -Xms256m -Xmx512m -XX:+UseG1GC  -jar /opt/blog-0.0.1-SNAPSHOT.jar

Restart=always
RestartSec=10

MemoryLimit=1200M
CPUQuota=80%

StandardOutput=journal
StandardError=journal
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

You can change the user to the system user you want to run the application with and change the java path.

Start the java application service with systemd

Reload the service so it gets new/changed service details. After that start the application and check the status.

sudo systemctl daemon-reload
sudo systemctl start blog.service
sudo systemctl status blog.service 

The status command will give you the output with the application running or not and some console output of the java -jar command.

To enable service at startup do:

sudo systemctl enable blog.service 

To restart the service do:

sudo systemctl restart blog.service

To get more details about systemd checkout

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/system_administrators_guide/chap-managing_services_with_systemd