Creating Systemd Units

If you work with RHEL/CentOS 7 or Ubuntu 15.04+, you're probably already familiar with systemd. Systemd is an init system, like Upstart, that allows you to manage services on your OS. The following is an example of how to restart a service (let's call it xyz) in an OS using systemd:

systemctl restart xyz

While understanding how to use the systemctl command is pretty straight forward, there will be times when you have applications or scripts of your own that you will want to manage using the systemctl command. I recently came across a forum where users were starting and backgrounding their apps with something along the lines of the following:

nohup ./myapplication > /dev/null 2>&1 &

While the nohup command works to background your application and allow you to exit the terminal, it is not a robust way of managing your application or script. For example, what will you do when you reboot the node and need the application to start back up again automatically?

The need above would be better served by managing the app using the systemctl command. So let's learn how to go about making this happen.

To start, you must create a systemd unit. A unit is basically a resource that systemd knows how to manage and is located in /etc/systemd/system with the .service suffix. Once you accomplish this, you will be able to start, stop, and enable the service (thus allowing it start back up automatically after reboot) using the systemctl command.

I'll use myapplication from the example above to create a systemd unit. We will then be able to run commands like systemctl start myapplication and systemctl enable myapplication.

Create a file called myapplication.service in /etc/systemd/system with the following content:

[Unit]
Description=My Application

[Service]
WorkingDirectory=/root/MyApplicationDirectory/
ExecStart=/root/MyApplicationDirectory/MyApplication
Restart=always

[Install]
WantedBy=multi-user.target

There are far more parameters and options you can set in a systemd unit file. To see more details, check out the following resource. For now, these parameters are enough to accomplish what we need.

Remember that anytime you create, modify, or delete a systemd unit file, you must issue the following command to reload systemd:

systemctl daemon-reload

Now you can start your application and enable it as well so it starts up automatically if you reboot the node. Do this by issuing the following commands:

systemctl start myapplication
systemctl enable myapplication

You can now run systemctl status myapplication to confirm the app has been started and enabled.