How to create a systemd target?

Reading through man 5 systemd.unit and man 5 systemd.target tells us that unit files are used to define targets as well as everything else systemd. There is no documentation specifically on how to create a target, so it's hard to determine the how it should be done, but it is not too different from creating a service.

When you create your target, you will need to make symlinks to the target.wants directory from the systemd services directory. Then you can set/boot your target. Here's how it might look given your example.

/etc/systemd/system/foo.target

This is the target's unit file. If graphical.target is taken as an example, we can create our own target using it as a base.

[Unit]
Description=Foobar boot target
Requires=multi-user.target
Wants=foobar.service
Conflicts=rescue.service rescue.target
After=multi-user.target rescue.service rescue.target
AllowIsolate=yes

To explain the options taken from the systemd manpages;

  • Description -- Describes the target. You should understand
  • Requires -- Hard dependencies of the target. You should let the basic system start before you start your own service(s)
  • Wants -- Soft dependencies. The target does not require these to start.
  • Conflicts -- If a unit has a Conflicts setting on another unit, starting the former will stop the latter and vice versa.
  • After -- Boots after these services
  • AllowIsolate -- Really up to you and your environment. Details are available in the manpage systemd.unit(5)

/etc/systemd/system/foo.target.wants/

This is the directory where you will link the services you create/require for your target. It is equivalent to the Wants= option in the unit file. Create this directory and then create symlinks like so; ln -s /usr/lib/systemd/system/bar.service /etc/systemd/system/foo.target.wants/bar.service. This creates a symlink from bar.service in the system directory to your foo.target.wants directory.


I think creating a unit file for a service is kind of out of the scope of this answer, and that question is definitely more documented so I'll leave that out for now. When you create your unit file, just symlink it into the target.wants directory or add it to the Wants= directive.