How to Create systemd service unit in Linux

How to Create systemd service unit in Linux

May 13, 2020 / Eternal Team

  • systemd is a Linux tool at first created by the Red Hat Linux group. It incorporates numerous highlights, including a bootstrapping system used to begin and oversee system forms. It is at present the default initialization system on most Linux appropriations. Numerous usually utilized programming apparatuses, for example, SSH and Apache, transport with a systemd administration.
  • It is easy to make a custom systemd service that will run any script or process you choose. In spite of the fact that there are a few different ways to run a content or start a procedure when your Linode boots, a custom systemd service makes it simple to start, stop, or restart your content, just as design it to begin naturally on boot. systemd offers the upside of utilizing an institutionalized interface that is reliable over all

Create a Custom systemd Service

  • Create a script or executable that the service will manage. This guide uses a simple Bash script as an example:
    • Test_service.sh
    • DATE=`date ‘+%Y-%m-%d %H:%M:%S’`
    • echo “Example service started at ${DATE}” | systemd-cat -p info
    • while :
    • Do
    • echo “Looping…”;
    • sleep 30;
    • Done

  • This script will log the time at which it is initialized, then loop infinitely to keep the service running.
  • Copy the script to /usr/bin and make it executable:
sudo cp test_service.sh /usr/bin/test_service.sh
sudo chmod +x /usr/bin/test_service.sh
  • Create a Unit file to define a systemd service:
    • Path : /lib/systemd/system/myservice.service
      • [Unit]
      • Description=Example systemd service.
      • [Service]
      • Type=simple
      • ExecStart=/bin/bash /usr/bin/test_service.sh
      • [Install]
      • WantedBy=multi-user.target

    • This defines a simple service. The critical part is the ExecStart directive, which specifies the command that will be run to start the service.
  • Copy the unit file to /etc/systemd/system and give it permissions :
sudo cp myservice.service /etc/systemd/system/myservice.service
sudo chmod 644 /etc/systemd/system/myservice.service

Start and Enable the Servicew

1. Once you have a unit file, you are ready to test the service

sudo systemctl start myservice

2. Check the status of the service:

sudo systemctl status myservice

3. The service can be stopped or restarted using standard systemd commands:

sudo systemctl stop myservice

4. Finally, use the enable command to ensure that the service starts whenever the system boots:

sudo systemctl enable myservice
AWS-Consulting-Partner

Talk to AWS Certified Consultant

Want to start a project?

It’s simple.

Contact us