fIn this post, I will show you how you can easily manage Java jar applications with Systemd service. Systemd is a system and service manager for Linux. It is now the default init system for a number of Distributions including Ubuntu 16.04/18.04, Debian 8/9, CentOS 7, Arch Linux e.t.c.
In this deployment, I have a Jar file located under a
/opt/prod/directory. As a rule of thumb, we need to add a system user which will run the application with systemd.
Step 1: Create an Application User and group
Start by creating a system group for the user.
sudo groupadd -r appmgr
Next, we create a system user
jvmapps with the default group
sudo useradd -r -s /bin/false -g appmgr jvmapps
Confirm user created and if with the correct group
# id jvmapps uid=992(jvmapps) gid=986(appmgr) groups=986(appmgr)
Step 2: Create Systemd Service
We can now create a systemd service file to manage our application. You need to create this file as root user.
sudo vim /etc/systemd/system/myapp.service
It will have content like below
[Unit] Description=Manage Java service [Service] WorkingDirectory=/opt/prod ExecStart=/bin/java -Xms128m -Xmx256m -jar myapp.jar User=jvmapps Type=simple Restart=on-failure RestartSec=10 [Install] WantedBy=multi-user.target
User to the one created earlier, and
WorkingDirectory to the directory with a jar file.
-Xmx256m are used to set the minimum and maximum memory that the application can use.
When done with the change, give the user and group ownership permissions for the Project Directory:
sudo chown -R jvmapps:appmgr /opt/prod
Step 3: Start Java Application service with systemd
The next thing to do is start the application service, but first, reload systemd so that it knows of the new application added.
sudo systemctl daemon-reload
Once reloaded, start the service
sudo systemctl start myapp.service
To check the status, use:
sudo systemctl status myapp
You can also enable the service to start on server boot
$ sudo systemctl enable myapp Created symlink from /etc/systemd/system/multi-user.target.wants/myapp.service to /etc/systemd/system/myapp.service.
To restart the application, use:
sudo systemctl restart myapp
You now have a Java Application being managed by Systemd. Replicate the same procedure for all other services you need to manage using Systemd init. Hope this was helpful, for any issues, let me know through the comments section.