Services with systemctl

Linux · Practical · 10 min

Nearly every server program runs as a systemd service, so systemctl is how you operate them.

systemd is PID 1 on almost all modern distributions. It starts and supervises units: services (.service), timers, mounts, sockets and targets (groups of units, like multi-user.target). You control them with systemctl:

  • systemctl status name shows whether it is running, its main PID, memory, cgroup and the latest log lines: the first command to run when something is wrong,
  • start, stop, restart, and reload (re-read configuration without a restart, if the service supports it),
  • enable makes it start at boot, disable stops that; enable --now does both enable and start,
  • is-active, is-enabled and is-failed give script-friendly answers,
  • systemctl --failed (or list-units --state=failed) lists broken units,
  • systemctl cat name shows the unit file and its overrides, systemctl show name every property.

Note the difference between running now (start/stop) and starting at boot (enable/disable); forgetting to enable is a classic "worked until the reboot" bug. mask prevents a unit from being started at all.

State-changing commands need sudo. Users can also run their own services with systemctl --user. Services log to the journal, which journalctl -u name reads.

Example

systemctl status nginx              # state, PID, memory, recent log lines
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx        # stop + start
sudo systemctl reload nginx         # re-read config, keep connections
sudo systemctl enable --now nginx   # start at boot AND right now
systemctl is-active nginx           # active
systemctl is-enabled nginx          # enabled
systemctl --failed                  # units that failed
systemctl cat nginx                 # the unit file and overrides
systemctl list-units --type=service --state=running | head
systemctl --user status syncthing   # a per-user service

Remember

  • status first; start/stop/restart/reload for now, enable/disable for boot
  • enable --now does both
  • systemctl --failed shows what is broken

Watch out for

  • Starting a service but never enabling it, so it is gone after the next reboot.

Check yourself

  1. Which command makes a service start at boot and also starts it immediately?
  2. What is `systemctl reload` for?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.freedesktop.org/software/systemd/man/latest/systemctl.html