Take a look at
Commands to execute to stop the service started via ExecStart=. This argument takes multiple command lines, following the same scheme as described for ExecStart= above. Use of this setting is optional. After the commands configured in this option are run, all processes remaining for a service are terminated according to the KillMode= setting (see systemd.kill(5)). If this option is not specified, the process is terminated by sending the signal specified in KillSignal= when service stop is requested. Specifier and environment variable substitution is supported (including $MAINPID, see above).
It is recommended to use this setting for commands that communicate with the service requesting clean termination. When the commands specified with this option are executed it should be assumed that the service is still fully up and is able to react correctly to all commands. For post-mortem clean-up steps use ExecStopPost= instead.
Additional commands that are executed after the service is stopped. This includes cases where the commands configured in ExecStop= were used, where the service does not have any ExecStop= defined, or where the service exited unexpectedly. This argument takes multiple command lines, following the same scheme as described for ExecStart=. Use of these settings is optional. Specifier and environment variable substitution is supported. Note that – unlike ExecStop= – commands specified with this setting are invoked when a service failed to start up correctly and is shut down again.
It is recommended to use this setting for clean-up operations that shall be executed even when the service failed to start up correctly. Commands configured with this setting need to be able to operate even if the service failed starting up half-way and left incompletely initialized data around. As the service's processes have been terminated already when the commands specified with this setting are executed they should not attempt to communicate with them.
Note that all commands that are configured with this setting are invoked with the result code of the service, as well as the main process' exit code and status, set in the $SERVICE_RESULT, $EXIT_CODE and $EXIT_STATUS environment variables, see systemd.exec(5) for details.
Both of these can be used to run commands when the service is stopped.
The main differences between the two:
ExecStop runs while the main process is still running, and will only run when the service is stopped after running normally (meaning all of the services
ExecStartPre must succeed, and any
must also pass.
ExecStopPost runs even if the "service exited unexpectedly", which covers failures. The biggest boon of this is when you have multiple
ExecStarts, if one of them succeeds and the other fails
ExecStopPost can be used to try to clean up the partial success.