Creating services with systemd
Tags: @systemd @service @system
Services are programs that run in the background, and can be set to run at boot.
Best practice to create a service is to first create a shell script called my-script.sh that we will tell our service to run at boot:
#!/bin/sh
echo Hello Faaiz
Now we copy the script to /usr/bin/ and make it executable by doing:
$ sudo cp my-script.sh /usr/bin/my-script.sh
$ sudo chmod +x /usr/bin/my-script.sh
Next, we need to create a Unit file to create the service that will run our script in the background, and save as my-service.service:
[Unit]
Description=This is my custom service
# ExecStart is where we tell it what script to use.
[Service]
Type=simple
ExecStart=/bin/sh /usr/bin/my-script.sh
[Install]
WantedBy=multi-user.target
Now, we move the service to etc/systemd/system and give it the required permissions:
$ sudo cp my-service.service /etc/systemd/system/my-service.service
$ sudo chmod 644 /etc/systemd/system/my-service.service
Finally we can run the following commands to start, stop, check status, and ensure that it starts on boot:
# Start service
$ sudo systemctl start my-service
# Stop service
$ sudo systemctl stop my-service
# Check status
$ sudo systemctl status my-service
# Enable at boot
$ sudo systemctl enable my-service