flakes flakes - 20 days ago 5
Linux Question

Systemd: Using both After and Requires

I have a service

foo.service
which depends on service
bar.service
. I need to make sure that
bar.service
is started before
foo.service
and that
bar.service
launched successfully.

From this source it says that
Requires
:


This directive lists any units upon which this unit essentially depends. If the current unit is activated, the units listed here must successfully activate as well, else this unit will fail. These units are started in parallel with the current unit by default.


and that
After
:


The units listed in this directive will be started before starting the current unit. This does not imply a dependency relationship and one must be established through the above directives if this is required.


Is it correct to have both the
Requires
and
After
sections in the same unit file?
Requires
says that the service will be launched in parallel, but
After
says it will be launched before. If
bar.service
fails to start during the
After
condition, will it attempt to launch it again during the
Requires
section? If so I need to find another way to launch
foo.service


foo.service


[Unit]
After=bar.service
Requires=bar.service

Answer

It is perfectly fine to use both After= and Requires=. They have different purposes. Requires= sets up a start dependency. systemd makes sure that if any body is trying to start foo.service, it should start bar.service too. Should bar.service fails at some point, then foo.service is taken down too.

After= is putting a start order between services. If both of the services are scheduled to start, then After= makes sure the start order is set.

You can look at systemd's own service file as an example.

/lib/systemd/system/basic.target [Unit] ... Requires=sysinit.target After=sysinit.target ...

Comments