devops beginner

How to check service health and restart if down

Question

How can I create a Perl script that monitors a service and automatically restarts it if it's not running?

Check process status and restart if needed:

#!/usr/bin/perl
use strict;
use warnings;

my $service = 'nginx';
my $check_cmd = "systemctl is-active $service";
my $status = `$check_cmd`;
chomp $status;

if ($status ne 'active') {
    print "Service $service is $status. Restarting...\n";
    system("systemctl restart $service");
    
    sleep 2;
    $status = `$check_cmd`;
    chomp $status;
    
    if ($status eq 'active') {
        print "Service $service restarted successfully.\n";
    } else {
        print "Failed to restart $service!\n";
    }
} else {
    print "Service $service is running.\n";
}

This script checks if a systemd service is active and attempts to restart it if down, then verifies the restart succeeded.

Was this helpful?

Related Questions