3

I have a web application that is started by systemd. It uses Postgresql as database, so it rely on it. Here is the unit file of my web application (I have remove the un-relevant/sensitive parts):

[Unit]
Description=xxxx
Requires=postgresql.service
After=network.target postgresql.service

[Service]
Type=simple
PermissionsStartOnly=true
SyslogIdentifier=xx-service
User=yyy
Group=zzz
ExecStart=/opt/.../xx
WorkingDirectory=/opt/xx
StandardOutput=journal+console

[Install]
WantedBy=multi-user.target

Host os is Ubuntu server 16.04.

I recently had an event where the web application was not running in the morning when I returned to work. After checking the logs, I discovered the service was stopped by systemd because postgresql had an update. Apparently aptitude stopped postgresql before the upgrade and restarted it rigth after the update. When I logged into the machine it was running.

But systemd decided to stop my web application before stopping postgresql, which is nice, but didn't restart the web app it after it restarted postgresql.

How to instruct systemd to restart the appliation after postgresql service is restarted ?

Antoine
  • 133
  • 1
  • 4

1 Answers1

4

I think you're looking for PartOf:

PartOf= Configures dependencies similar to Requires=, but limited to stopping and restarting of units. When systemd stops or restarts the units listed here, the action is propagated to this unit. Note that this is a one-way dependency — changes to this unit do not affect the listed units.

When PartOf=b.service is used on a.service, this dependency will show as ConsistsOf=a.service in property listing of b.service. ConsistsOf= dependency cannot be specified directly.

Add PartOf=postgresql.service to the unit file of your web application, reload systemctl-daemon and test.

And to address the situation where your web application will have to start automatically after postgresql.service gets started, you could combine PartOf with Wants, but in postgresql's unit file:

Wants= A weaker version of Requires=. Units listed in this option will be started if the configuring unit is. However, if the listed units fail to start or cannot be added to the transaction, this has no impact on the validity of the transaction as a whole. This is the recommended way to hook start-up of one unit to the start-up of another unit.

Note that dependencies of this type may also be configured outside of the unit configuration file by adding symlinks to a .wants/ directory accompanying the unit file. For details, see above.

13dimitar
  • 2,360
  • 1
  • 12
  • 15
  • This works if i do `systemctl restart postgresql` but not if I `systemctl stop postgresql` then `systemctl start postgresql` as the automatic update will do. – Antoine Feb 13 '18 at 11:32
  • 1
    I used `WantedBy=` as I didn't want to mess system components (ubuntu provided unit file) and now it works. Also I think its a more modulare approach. @13dimitar Thanks for you help ! – Antoine Feb 13 '18 at 13:24