How to Run a Script as a Service in Linux Distro in Reliable way

      Comments Off on How to Run a Script as a Service in Linux Distro in Reliable way

Linux administrators mostly face some cases where they need to run a script as a service. This includes some custom monitoring scripts to trigger some failover jobs.

Here we see how we can run a script as a service in centos server.

[[email protected] ~]# vim /opt/devopstree.sh
[[email protected] ~]# cat /opt/devopstree.sh 
while true; do
    echo "Hello world" > /var/log/helloworld.log
    sleep 60s
done
[[email protected] ~]#

To run this script as a service, all we need to do is create a systemd service file under /etc/systemd/system/ directory,

[[email protected] ~]# vim /etc/systemd/system/helloworld.service
[[email protected] ~]#
[[email protected] ~]# cat /etc/systemd/system/helloworld.service
[Unit]
Description=Hello World
Requires=network-online.target
After=network-online.target
ConditionFileNotEmpty=/opt/devopstree.sh

[Service]
EnvironmentFile=/etc/sysconfig/helloworld
Environment=GOMAXPROCS=2
Restart=on-failure
ExecStart=/bin/bash /opt/devopstree.sh
StandardOutput=/var/log/helloworld.log
StandardError=/var/log/helloworld.log
LimitMEMLOCK=infinity
ExecReload=/bin/kill -HUP $MAINPID
KillSignal=SIGTERM

[Install]
WantedBy=multi-user.target
[[email protected] ~]#

Once you saved this file your script can be start as a service. You can just start it like a normal service.

You can even enable this service to run in boot time,

[[email protected] ~]# systemctl enable helloworld.service
Created symlink from /etc/systemd/system/multi-user.target.wants/helloworld.service to /etc/systemd/system/helloworld.service.
[[email protected] ~]# 
[[email protected] ~]# systemctl is-enabled helloworld.service
enabled
[[email protected] ~]# 

That’s It. Now our script is running a service.

Also we can use setsid command run a script as a service,

SETSID Example:

setsid /opt/devopstree.sh >/var/log/helloworld.log 2>&1 < /dev/null &

But systems service file is the best way to do this. Which way you prefer, Leave your comments below.

Sharing is caring!

About Dinesh Sobitharaj C

An IT professional having multiple years of experience in IT Infrastructure planning, System integrations, Project implementation and delivery. Devops Enthusiast skilled with broad ranges of technology adoption. Well versed with Cloud Computing and Application Service Offerings such as SaaS/PaaS/IaaS. Expert in aligning business goals, mission and process to architect innovative solutions and strategies.