21

I want a quick and easy way to tell how many times a service managed by systemd has restarted (i.e. like a counter). Does that exist?

1
  • cool, how do we tell systemd that the process is stable? like a health check? Mar 22, 2020 at 3:38

2 Answers 2

27

The counter has since been added and can be accessed with the following command:

systemctl show foo.service -p NRestarts

It will return a value if the service is in a restart loop, otherwise, will return nothing.

https://github.com/systemd/systemd/pull/6495

4
  • cool, how do we tell systemd that the process is stable? like a health check? Mar 22, 2020 at 3:38
  • @AlexanderMills The counter mentioned in this answer only increments if it is restarting over and over. To check if the service is running, you can use systemd is-active Mar 23, 2020 at 15:35
  • Note that NRestarts only counts automatic restarts triggered by systemd (e.g. because the service crashed), but not manual restarts triggered by systemctl restart. It is therefore useful to track down crashing services, but it won't help you if a faulty shell script restarts a service in an endless loop. Sep 27, 2023 at 15:07
  • Note that NRestarts was introduced in systemd version 235, so the earlier versions should find another workaround.
    – AnonymousX
    Jan 1 at 15:40
10

systemctl shows the last start time (or uptime) of the service. But that's not enough for telling how many times the service was restarted.

The following command can probably show you the number of starting (or restart) occurrences:

journalctl -u <service_name>.service | grep Starting

For example:

$ journalctl -u foo.service | grep Starting
Jul 24 16:09:56 10.16.26.1 systemd[1]: Starting foo...
Jul 25 18:12:14 10.16.26.1 systemd[1]: Starting foo...

And this command just gives you a count of the number of restarts:

journalctl -u <service_name>.service | grep Starting | wc -l

For example:

$ journalctl -u foo.service | grep Starting | wc -l 
2

Note: you can vary the string you use here. You could use this 'Started' to tell if the service successfully started. Or you could use '<service_name>.service failed' to tell the number of occurrences that the service failed.

Also, its interesting to note that they've been discussing the idea of adding a counter to systemd on GitHub:

https://github.com/systemd/systemd/issues/4126

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .