How to create a virtual systemd service to stop/start several instances together?

I learned that this what systemd "Target Units" are for. By using a Target Unit, I get the benefits I want without needing to create the fake [Service] section I had above. A working example "Target Unit" file looks like this:

# named like app.target
[Unit]
Description=App Web Service

# This collection of apps should be started at boot time.
[Install]
WantedBy=multi-user.target

Then each customer instance should include PartOf in the [Unit] section (as pointed out by @meuh), and should also have an [Install] section so that enable and disable will work on the specific service:

# In a file name like [email protected]
[Unit]
Description=%I Instance of App Web Service
PartOf=app.target

[Service]
ExecStart=/home/mark/bin/app-poc.sh %i
Restart=on-failure
StandardOutput=journal

# When the service runs globally, make it run as a particular user for added security
#User=myapp
#Group=myapp

# When systemctl enable is used, make this start when the App service starts
[Install]
WantedBy=app.target

To bring up the customer instance and have it start when the target is started, this one-time enable command is used:

 systemctl enable app

Now at this point I can use stop and start on app@customer to for a specific instance, or I can use start app and stop app to stop all the apps together.


You need to move the line

PartOf=app.service

out of [Service] and into the [Unit] section, and add to the [Unit] of app.service the list of customers to start, eg

[email protected] [email protected]

or as sourcejedi said in the comments, Requires= the same thing. You can keep the PartOf to stop services you start by hand that are not in the above list, like systemctl --user start [email protected].

Tags:

Ubuntu

Systemd