Sunday, April 8, 2018

Run programs as services in Ubuntu System

BRIEF INTRODUCTION

Running jobs from bash terminal is really easy. But what if we want to reduce user interaction to implement automation, we define services which run on its own. We do not need to run or click to start the program. Once we define the service and enable it, then the program runs when operating system boots. The service programs in the background, and they do not terminate when user logs out. That means, these service programs are running in the background and users do not notice them.  And they are quite handy to start and stop from remote system, or from terminal. After the job is started, we can safely disconnect remote system or close the terminal.


PROCEDURE

Now, we start creating a service that runs on the background. The perfect example would be running tomcat as a service because it need it always running, at the same time, we need to start or restart from time to time. Also we need to auto-start when system is rebooted.

So, we create a service that starts and stops tomcat server. To implement that, we first of all install Tomcat Server. I will not talk about tomcat installation here, it really straight forward. Just download packaged tomcat installer and extract the files into /opt/tomcat.

We could manually start and stop from the command in bin directory of tomcat folder. But that is not what we want. Basically we create a service and configure it so that it starts automatically when system reboots.  So, first task we do is, to create a tomcat.service file

The file looks something like this:

File: tomcat.service

[Unit]
Description=Tomcat Service
After=network.target

[Service]
Type=forking
ExecStart=/opt/tomcat/bin/catalina.sh start
ExecStop=/opt/tomcat/bin/catalina.sh stop
RestartSec=10
Restart=always

[Install]
WantedBy=multi-user.target
               

So, after this file is created, we copy this file into /lib/systemd/system/ directory and load daemon

sudo systemctl  daemon-reload

TESTING

So,  to just start service, we use the command

sudo systemctl start tomcat (starts  service)
sudo systemctl status tomcat (gets status)
sudo systemctl is-active tomcat
sudo systemctl is-enabled tomcat
sudo systectl enable tomcat (!Enables the service)

And we can simply start or stop service  in traditional way too as follows:

sudo service tomcat start
sudo service tomcat stop
sudo service tomcat status


In case I need to start service after sytem boot, I enable the service. Otherwise, I just use the command start and stop to start and stop service.

The file uses the basic configuration, we can extend it and add more configuration.



References:

https://wiki.ubuntu.com/SystemdForUpstartUsers

No comments:

Post a Comment