start systemd service on start of requirement

I have a service which depends on mysql.service via Requires=. This is necessary, because the service crashes, if mysql is not available.

Executing systemctl restart mysql works fine. It stops my service first, restarts mysql and starts my service again.

How can I configure my unit, that it is also started again, if I run systemctl stop mysql && systemctl start mysql?

This is especially a problem during debian’s unattended-upgrades of mysql, because the update-process uses stop/start and not restart.



new and better answer

Clearly i have not been reading well yesterday. It seems your problem can easily be solved by adding mysql.service to your services WantedByunder the [Install] section.

then after you reenable your service, it should be started whenever mysql.service is started, as long as your service is enabled

the result looks like this:

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

[Install]
WantedBy=multi-user.target mysql.service

my old answer for reference:

I don't know if it is possible to configure your unit to behave the way you want it to.

I have, however, solved similar problems by installing systemd drop-in files to modify the foreign unit, in your case mysql.service.

assuming your unit is foo.service you could create a .conf file in
/etc/systemd/system/mysql.service.d/ with the following content:

[Unit]
Wants=foo.service
Before=foo.service

this would cause systemd to try and start foo.service after every start of mysql.service

for completeness sake, and to quote systemd documentation:

In addition to /etc/systemd/system, the drop-in ".conf" files for system services can be placed in /usr/lib/systemd/system or /run/systemd/system directories. Drop-in files in /etc take precedence over those in /run which in turn take precedence over those in /usr/lib. Drop-in files under any of these directories take precedence over unit files wherever located. (Of course, since /run is temporary and /usr/lib is for vendors, it is unlikely drop-ins should be used in either of those places.)