Thursday, November 8, 2018

Configure a Linux Service to Start Automatically After a Crash or Reboot

Configure a Linux Service to Start Automatically After a Crash or Reboot

Below articles defines how to start a service automatically after restart or server or when service is stopped by some other service or accidental user kill.

Note: this will work only with systemd

If service are enable under systemctl, service will start automatically after system reboot. However it does not restart when service was killed accidentally or by any other process.

To check if the service enable for auto restart run below command ( in this case I am running for mongodb)

systemctl status mongod.serivce

output should contain "mongod.service; enabled;" if yes you are good at server restart.
If not run below command to enable service:
systemctl enable mongod.serivce

Below are the steps to enable service to start automatically after unexpected service down:

1. open below file using text editor for mongodb for other serivces use different service name instead of mongod


/etc/systemd/system/multi-user.target.wants/mongod.service


2. Add "Restart=always" under [Service] section of the file, save and close the file.
3. Reload the systemctl demon


sudo systemctl daemon-reload


4. Restart the service in this case mongodb service


systemctl restart mongod.service

For testing we can kill the service, below are steps:
6. Get the pid with the help of below command for mongodb 


ps -ef | grep service


7. kill the process with the help process number which we have received from above command.


kill -9 process_number


8. wait for a second or two and run below command to check the status of serivce in this case mongodb.


systemctl status mongod.service


Note: All the information provided in this article is based on my experience usage or application  based on your own interest.

Thanks for the checking in yours Nag.

Configure a Linux Service to Start Automatically After a Crash or Reboot

Configure a Linux Service to Start Automatically After a Crash or Reboot Below articles defines how to start a service automatically after ...