Create a Systemd service in Linux

Most of us are familier with applications in Windows like Word, Notepad etc. To use a Word application, it is not enough to install it. After the installation, we open (start) a Word application, use it and then later close it. Similarly, in Linux, we can treat similar applications like services. We can do several operations like start, status, restart and stop etc.

Let us create a simple service.
a) Create a script (bash)

Open terminal and create a script named hello.sh
vim hello.sh

Now, let’s create a bash file which prints some text. ( under /home/user/test )

#!/bin/bash
while :
do
    echo "test service.. mike testing"
    sleep 10
done

Give executable permission to this file
chmod +x /home/user/test/hello.sh

b) Create a service file

Under /etc/systemd/system/ , create a service file
vim hello.service

We have 3 sections when creating a service file
 1) Unit 2) Service 3) Install. For now, we shall just go with the mandatory one.

[Service]
ExecStart=/home/pi/test/hello.sh

c) Do operations on that service: start, status, stop

To start the service
sudo systemctl start hello

To check status
sudo systemctl status hello

To stop service
sudo systemctl stop hello

Add more stuff to the service file

[Unit]
Description=My first service to test

[Service]
ExecStart=/home/pi/test/printname.sh
Restart=always
WorkingDirectory=/home/pi/test
User=pi
Group=pi

[Install]
WantedBy=multi-user.target

Here, we are providing following:
Giving a discription to our service file
Specifying our working directory
Specifying user and group name etc.

Comments

Popular posts from this blog

Pentaho ETL

Copy files from one computer to other using ‘scp’ command