Linux – What’s the systemctl equivalent for a command like ‘chkconfig –level 5 iptables on’

chkconfiglinuxsystemd

I know systemctl enable iptables is similar to the command chkconfig --level 5 iptables on, but both are not exactly same.

Using systemctl, how do we restrict a service to be started only on a given target like graphical.target.

Best Answer

That's what the WantedBy= and RequiredBy= directives in systemd unit files are for:

From man systemd.unit:

WantedBy=, RequiredBy=

This option may be used more than once, or a space-separated list of unit names may be given. A symbolic link is created in the .wants/ or .requires/ directory of each of the listed units when this unit is installed by systemctl enable. This has the effect that a dependency of type Wants= or Requires= is added from the listed unit to the current unit. The primary result is that the current unit will be started when the listed unit is started. See the description of Wants= and Requires= in the [Unit] section for details.

So the symbolic link created is what causes systemd to start the given unit when the target/unit is started.


So for example:

[Install]
WantedBy=graphical.target

Would cause the unit to only be started when graphical.target is run (if the unit is enabled).


Another example:

[Install]
WantedBy=my-custom-target.target graphical.target

Would cause the unit to be started when my-custom-target.target or graphical.target is run (if the unit is enabled).


One final thing to keep in mind, it can be difficult to restrict things to a single target because some targets depend on others. For example, graphical.target Requires=multi-user.target, so when graphical.target is started all units from multi-user.target are also started. Just keep in mind that some targets are built up on top of others, and that the ones built on top will get everything from the targets they depend on.

Related Question