Systemd Before and After declarations

dependenciesservicessystemd

The definition given in the man for systemd unit is a bit unclear: https://www.freedesktop.org/software/systemd/man/systemd.unit.html

If a unit foo.service contains a setting Before=bar.service and both
units are being started, bar.service's start-up is delayed until
foo.service is started up.
[…]
After= is the inverse of Before=, i.e. while After= ensures that the
configured unit is started after the listed unit finished starting up,
Before= ensures the opposite, that the configured unit is fully
started up before the listed unit is started.

Lets say I have a.service and b.service. I want a.service to start up completely before b.service because b.service depends on a.service.

After reading the aforementioned man page I couldn't find any conclusive explanation on whether:

  • You only need to specify Before=b.service in the a.service unit file
  • You only need to specify After=a.service in the b.service unit file
  • You need both After=a.service in the b.service unit file and Before=b.service in the a.service unit file

Which do I need to declare dependencies for systemd unit files? Does it matter?

Best Answer

You only need one of After= or Before= in your pair of units. You might prefer this from the man page for systemctl:

--after ... any After= dependency is automatically mirrored to create a Before= dependency.

Use this option with list-dependencies to check what you think systemd should be doing. Eg

$ systemctl list-dependencies --after timers.target
timers.target
* |-sysstat-collect.timer
* |-sysstat-summary.timer
* |-systemd-tmpfiles-clean.timer
* `-unbound-anchor.timer

$ systemctl list-dependencies --before sysstat-collect.timer
sysstat-collect.timer
* |-sysstat-collect.service
* |-shutdown.target
* `-timers.target

If you are converting from upstart you might get some hints from here, and you could read all the blogs listed here under the heading The systemd for Administrators Blog Series.

Related Question