systemctl is the command that drives the services of a Linux server: it lists them, starts them, stops them, reloads them and helps you understand why one of them fails. This page covers the life cycle of a service, the two ways to list services, how to write a service unit and how to diagnose a service that refuses to run. It is written both for someone discovering systemctl and for someone who has already been fooled by an over-optimistic start.
A few words of vocabulary before we start. systemd is the program that boots the machine, then starts and supervises the services (it is process number 1). A unit is an object that systemd manages: a service, a timer, a mount point, a target. Each unit is described by a text file, the unit file, and a service is the unit that describes a program to run in the background, such as nginx.
All the outputs shown here come from a Debian 13 server with systemd 257 and nginx installed. The commands are identical on Ubuntu, Debian and RHEL; only a few enable outputs differ, and this is pointed out.
What you will learn
- List services with
list-unitsandlist-unit-files, and understand why the two lists differ - Drive the life cycle of a service:
start,stop,restart,reload,status - Read a status line by line and query a service with
is-active,is-enabled,is-failed - Make a service start automatically at boot with
enable, disable or mask it, and readis-enabledwithout being misled - Understand which target (
WantedBy=) starts the service and prove with a reboot that it comes back - Write a custom service unit without falling into the
Type=simpletrap - Diagnose a failure with
journalctland the203/EXECcode
Prerequisites
You know how to open a Linux terminal, you have sudo, and you know what a process is. To understand where systemd and its units come from, read the page systemd: understand the Linux service manager first.
The five everyday commands
Most of the daily work on services fits in five commands. Each one acts immediately, on the system as it runs right now, and none survives a reboot of the machine: enabling at boot is a separate notion, covered below. All of them change the state of the system and therefore need sudo, except status, which only reads.
sudo systemctl start nginx # start nowsudo systemctl stop nginx # stop nowsudo systemctl restart nginx # stop then start againsudo systemctl reload nginx # reread the configuration without cuttingsystemctl status nginx # where do we stand?Get into the habit of chaining the action and its check on the same command line. The shell only runs the second command if the first one succeeded, and is-active answers in one word:
sudo systemctl start nginx && systemctl is-active nginxactiveThe .service suffix is optional: without a suffix, systemctl appends .service, so systemctl start nginx and systemctl start nginx.service are equivalent. The suffix becomes necessary to target another unit with the same name, such as a timer (a unit that triggers an action at a set time, see systemd timers) or a socket. For example, systemctl status logrotate shows the service, and only systemctl status logrotate.timer shows the schedule.
Reload without cutting traffic
reload asks the service to reread its configuration while it keeps serving the requests in progress. restart stops the process then starts a new one, and the open connections drop. On a production web server, the difference shows in the client logs.
sudo systemctl reload nginx && systemctl is-active nginxactiveRead a status line by line
systemctl status is the identity card of a service: where its unit file comes from, whether it runs, since when, with which PID (the number that identifies a process) and the last lines of its journal. It is the first reflex in front of a suspicious service.
systemctl status nginx● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: enabled) Active: active (running) since Fri 2026-11-13 15:05:40 UTC; 2min 11s ago Invocation: c2c33851f76949e18cc220fd7263ca4e Docs: man:nginx(8) Main PID: 2824 (nginx) Tasks: 3 (limit: 2095) Memory: 3M (peak: 7M) CPU: 27ms CGroup: /system.slice/nginx.service ├─2824 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;" ├─2826 "nginx: worker process" └─2827 "nginx: worker process"
Nov 13 15:05:40 lpg-debian.lab systemd[1]: Starting nginx.service - A high performance web server and a reverse proxy server...Nov 13 15:05:40 lpg-debian.lab systemd[1]: Started nginx.service - A high performance web server and a reverse proxy server.Look at the Loaded and Active lines first: most of the time they are enough to tell whether the service is installed, enabled at boot and running. The table gives the meaning of each line. On AlmaLinux 10.2, the Loaded line of nginx ends with preset: disabled: the service is indeed enabled, but the distribution does not enable it by default, whereas Debian 13 does.
| Line | What it tells you |
|---|---|
| Loaded | Path of the unit file in use, and whether the service is enabled at boot (enabled / disabled / masked) |
| Active | Current state and duration: active (running), inactive (dead), failed |
| Process | Commands already finished and their exit code (status=0/SUCCESS or an error); it does not appear in the nginx status above, but it does in the status of demo further down |
| Main PID | PID of the main process; if it is missing, nothing runs |
| CGroup | The cgroup of the service, that is, the kernel control group in which systemd puts all its processes, with the real tree of those processes |
The Loaded line is the one people forget to read. It gives the exact path of the loaded unit file, which keeps you from editing a file that systemd does not use, for example a copy under /usr/lib/systemd/system while a higher-priority version exists under /etc/systemd/system.
One-word answers
In a script, a full status is unusable: you need a short answer and a reliable exit code. Three commands provide it, whether you run them by hand or from an automation, for example with the Ansible systemd_service module (in French) or a deployment script.
systemctl is-active nginx # active | inactive | failed | activatingsystemctl is-enabled nginx # enabled | disabled | static | maskedsystemctl is-failed demo # failed if the unit is in failureWhen a service is in failure, reset-failed clears that state. After that, is-failed answers with the current state:
systemctl reset-failed demo && systemctl is-failed demoinactiveList services: list-units or list-unit-files?
A first surprise awaits anyone looking for "the list of services": there are two of them, they do not contain the same things, and the command found everywhere (systemctl list-units) hides part of the services of the machine.
The distinction fits in one sentence. list-units lists the units loaded in memory by systemd; list-unit-files lists the unit files installed on disk. A service installed by a package but never started exists on disk without systemd having loaded it, so it does not appear in list-units. On the demonstration server, the gap is clear: 43 loaded services against 156 installed unit files.
Services loaded in memory
systemctl list-units --type=service answers the question "what is systemd handling right now?". It is the runtime view, the one you want when you inspect a live server.
systemctl list-units --type=service UNIT LOAD ACTIVE SUB DESCRIPTION apparmor.service loaded active exited Load AppArmor profiles dbus.service loaded active running D-Bus System Message Bus● demo.service loaded failed failed Demo qui echoue nginx.service loaded active running A high performance web server and a reverse proxy server ssh.service loaded active running OpenBSD Secure Shell server systemd-journald.service loaded active running Journal Service systemd-modules-load.service loaded active exited Load Kernel Modules systemd-udevd.service loaded active running Rule-based Manager for Device Events and Files(... 35 more lines ...)
43 loaded units listed. Pass --all to see loaded but inactive units, too.To show all installed unit files use 'systemctl list-unit-files'.The full list has 43 lines. The excerpt keeps only eight of them, copied as they are. Three columns carry the useful information. LOAD says whether the unit file was read correctly. ACTIVE gives the general state and SUB the detail: a service in active (exited) finished its task successfully and left no process behind, which is normal for a start-up task. The black dot at the start of a line flags a unit that needs a look, here demo.service in failed: it is the demonstration unit whose ExecStart= points to a missing file, diagnosed further down.
The last two lines of the output are a user manual that systemd gives you: --all adds the units that are loaded but inactive, and list-unit-files shows everything that is installed.
Services installed on disk
systemctl list-unit-files --type=service answers the question "what is installed on this machine, and will it start at boot?". It is the disk view, the one you want for an audit or to find a service you never started.
systemctl list-unit-files --type=serviceUNIT FILE STATE PRESETapparmor.service enabled enabledapt-daily-upgrade.service static -autovt@.service alias -console-getty.service disabled disabledcryptdisks.service masked enablednginx.service enabled enabledserial-getty@.service indirect enabledsystemd-remount-fs.service enabled-runtime enabled(... 148 more lines ...)
156 unit files listed.The full output has 156 unit files; the excerpt above shows one example of seven of the eight states in the table, and generated does not appear on this machine. Read the STATE column first: it says what systemd will do with this service at the next boot of the machine. The PRESET column shows what the distribution recommends by default, which lets you spot the services whose state was changed by hand. The table details each state; a symbolic link is a small file that points to another file.
| STATE | What it means |
|---|---|
enabled | Will start at boot: a symbolic link exists in a .wants directory |
disabled | Will not start at boot, but can still be started by hand |
static | No [Install] section: cannot be enabled, it is pulled in by a dependency |
masked | Linked to /dev/null: impossible to start, even manually |
alias | Another name for an existing service (on Debian, kmod.service is a link to systemd-modules-load.service) |
enabled-runtime | Enabled until the next reboot only, the enabling lives in /run and not in /etc |
indirect | Not enabled itself, but it has a non-empty Also= directive, or a symbolic-link alias that Also= does not list. For a template unit (a name@.service file whose instances are enabled), an instance other than the one named by DefaultInstance= is enabled |
generated | Built on the fly by a generator, typically from an old SysV script (the former boot system, based on scripts) |
The serial-getty@.service case in the listing illustrates indirect for a template. Its [Install] contains WantedBy=getty.target but no DefaultInstance=. The systemd getty generator nevertheless enables the instance serial-getty@ttyS0.service, which returns enabled-runtime with systemctl is-enabled. The template itself therefore returns indirect: an instance other than the DefaultInstance= one is enabled. Conversely, getty@.service carries DefaultInstance=tty1 and returns enabled. This definition comes from the systemctl manual, and the measurements come from Debian 13, AlmaLinux 10.2 and Ubuntu 26.04 (systemd 257 on the first two).
The static state often surprises people. A systemctl enable systemd-tmpfiles-clean.service does nothing, and that is not a mistake on your side: this service is not meant to be enabled, other units trigger it. The command confirms it in one word.
systemctl is-enabled systemd-tmpfiles-clean.servicestaticThe listings that really help
Listing the 156 unit files of a server has little operational value. What you want is to filter: which services run, which ones fell over, which ones will start at the next boot. The --state= filter applies to both commands, with different values since they do not talk about the same thing.
For the services that run, with a live process:
systemctl list-units --type=service --state=running UNIT LOAD ACTIVE SUB DESCRIPTION dbus.service loaded active running D-Bus System Message Bus getty@tty1.service loaded active running Getty on tty1 incus-agent.service loaded active running Incus - agent nginx.service loaded active running A high performance web server and a reverse proxy server polkit.service loaded active running Authorization Manager serial-getty@ttyS0.service loaded active running Serial Getty on ttyS0 ssh.service loaded active running OpenBSD Secure Shell server systemd-journald.service loaded active running Journal Service systemd-logind.service loaded active running User Login Management systemd-networkd.service loaded active running Network Configuration systemd-resolved.service loaded active running Network Name Resolution systemd-udevd.service loaded active running Rule-based Manager for Device Events and Files user@1002.service loaded active running User Manager for UID 1002
Legend: LOAD → Reflects whether the unit definition was properly loaded. ACTIVE → The high-level unit activation state, i.e. generalization of SUB. SUB → The low-level unit activation state, values depend on unit type.
13 loaded units listed.For the services that will start at the next boot, the command to know for a server audit:
systemctl list-unit-files --type=service --state=enabledUNIT FILE STATE PRESETapparmor.service enabled enabledcloud-config.service enabled enabledcloud-final.service enabled enabledcloud-init-local.service enabled enabledcloud-init-main.service enabled enabledcloud-init-network.service enabled enablede2scrub_reap.service enabled enabledgetty@.service enabled enabledgrub-common.service enabled enablednginx.service enabled enabledssh.service enabled enabledsshd-keygen.service enabled enabledsystemd-network-generator.service enabled enabledsystemd-networkd-wait-online.service enabled enabledsystemd-networkd.service enabled enabledsystemd-pstore.service enabled enabledsystemd-resolved.service enabled enabledufw.service enabled enabled
18 unit files listed.For the failed services, the first reflex when you take over a machine you do not know:
systemctl list-units --state=failed UNIT LOAD ACTIVE SUB DESCRIPTION● demo.service loaded failed failed Demo qui echoue
Legend: LOAD → Reflects whether the unit definition was properly loaded. ACTIVE → The high-level unit activation state, i.e. generalization of SUB. SUB → The low-level unit activation state, values depend on unit type.
1 loaded units listed.Two options complete these commands. --all adds the units that are loaded but inactive, which takes the list from 43 to 107 entries on the demonstration machine: the stopped services reappear. --no-legend removes the header and the legend, which makes the output usable in a script, for example to count the lines.
systemctl list-units --type=service --no-legend | wc -l43The table that prevents the mistake
Each command asks a precise question, and the table pairs them up. In front of an unknown server, start from the question, then pick the command.
| You want to know | Command | Watch out |
|---|---|---|
| What runs right now | systemctl list-units --type=service --state=running | Does not show services installed but never started |
| Everything systemd has loaded | systemctl list-units --type=service | Add --all to include inactive units |
| What is installed on the machine | systemctl list-unit-files --type=service | The longest list, it is the disk view |
| What will start at the next boot | systemctl list-unit-files --type=service --state=enabled | The right command for an audit |
| What fell over | systemctl list-units --state=failed | The first diagnostic reflex |
| Find a service by name | systemctl list-unit-files | grep docker | Search the unit files, not the loaded units |
The states of a service
A service goes through several states during its life, and systemctl status shows them on the Active line. Knowing them avoids false diagnoses: a service in active (exited) is not broken, it simply finished its work.
| State | Meaning |
|---|---|
active (running) | The service runs, a process is alive |
active (exited) | The task finished successfully, no process remains (Type=oneshot) |
inactive (dead) | The service is stopped, without error |
failed | The service failed, the journal holds the reason |
activating | Start-up in progress |
deactivating | Shutdown in progress |
masked | The service is blocked, a start will refuse to do anything |
enabled is not active
This is the starting confusion of many beginners, and it produces servers that run fine until the first reboot. The two notions are independent: one talks about the present, the other about the next boot of the machine.
| Concept | Question asked | Command |
|---|---|---|
active | Is the service running right now? | systemctl is-active nginx |
enabled | Will it start on its own at the next boot? | systemctl is-enabled nginx |
The two notions combine freely, and every combination exists in operations.
| Combination | What it means |
|---|---|
| active + enabled | Runs and will come back at boot: the normal state of a production service |
| active + disabled | Runs, but will disappear at reboot: the classic trap after an installation |
| inactive + enabled | Stopped now, will come back at the next boot: typical after a maintenance stop |
| inactive + disabled | Stopped and will not come back: a service deliberately set aside |
The case that costs an incident is the second one. systemctl start nginx starts the service right away and writes nothing to disk. The server reboots three weeks later for a kernel patch, the service does not come back, and nobody links it to the installation. This happens to anyone who installs a service on a Friday evening and finds it stopped on Monday.
The diagram separates the two axes. On the left, the state right now, changed by start and stop. On the right, the state at the next boot, changed by enable, disable and mask. No arrow links the two columns: that is the point to remember.
Enable a service at boot
Three commands are enough day to day. enable creates the symbolic link that will start the service with the machine, enable --now creates it and starts the service immediately, and disable removes the link.
sudo systemctl enable nginx # at the next bootsudo systemctl enable --now nginx # at the next boot AND nowsudo systemctl disable nginx # will no longer start at bootsystemctl is-enabled nginx # checkThe output of enable depends on the distribution, which is confusing the first time. On RHEL, systemd prints the symbolic link it created. On Debian and Ubuntu, a package that still ships a SysV script (nginx does) first triggers a synchronization: two lines talk about SysV before the message about the link. On Debian 13, here is enable when the link does not exist yet:
Synchronizing state of nginx.service with SysV service script with /usr/lib/systemd/systemd-sysv-install.Executing: /usr/lib/systemd/systemd-sysv-install enable nginxCreated symlink '/etc/systemd/system/multi-user.target.wants/nginx.service' → '/usr/lib/systemd/system/nginx.service'.The disable prints the same SysV lines, then the removal of the link, which confirms the underlying mechanism:
Synchronizing state of nginx.service with SysV service script with /usr/lib/systemd/systemd-sysv-install.Executing: /usr/lib/systemd/systemd-sysv-install disable nginxRemoved '/etc/systemd/system/multi-user.target.wants/nginx.service'.In every case, the only reliable check is systemctl is-enabled nginx, which must answer enabled. Do not trust the message printed, trust the state.
Why "Created symlink" does not always appear
Running enable again on a service that is already enabled prints only the two SysV lines, and it looks like a failure. There is none: enable is idempotent. If the link already exists, systemd has nothing to create and writes nothing more.
sudo systemctl enable nginxSynchronizing state of nginx.service with SysV service script with /usr/lib/systemd/systemd-sysv-install.Executing: /usr/lib/systemd/systemd-sysv-install enable nginxOn a unit without a SysV script, which covers most modern services and is the general case on RHEL or Fedora, those two lines disappear and only Created symlink remains. The message therefore depends on the package and on the previous state: it proves nothing.
Enable and start in one command
enable --now adds a start to the enabling. It is the form to use at installation, because it removes a classic oversight. Then check both states, not just one:
sudo systemctl enable --now nginxsystemctl is-active nginx && systemctl is-enabled nginxactiveenabledCheck enabling in a script
is-enabled prints the state and also sets an exit code that automation can use. With --quiet, the command prints nothing and returns 0 if the service is enabled.
systemctl is-enabled --quiet nginx; echo "code=$?"code=0Beware of the trap: is-enabled also returns 0 for the static, alias, indirect, generated and transient states, not only for enabled. A loop that only tests the exit code can therefore validate a static unit, which will not start by itself at boot. For a real compliance check on critical services, compare the printed string with enabled (or enabled-runtime), not just $?.
Disable without stopping the service
disable removes the symbolic link, so the service will no longer come back at boot. It keeps running if it was active: disable stops nothing. To disable and stop in one go, use disable --now, then check with systemctl is-enabled nginx, which must answer disabled.
Mask a service for good
disable prevents automatic start-up, but leaves the door open to a manual systemctl start, including one triggered by the dependency of another service. mask closes the door: systemd creates a link to /dev/null, and nothing can start the service any more.
sudo systemctl mask nginxCreated symlink '/etc/systemd/system/nginx.service' → '/dev/null'.Any start attempt then fails with an unambiguous message. That is the behavior you want for a service that must never run on a server, such as Bluetooth, Avahi or CUPS:
Failed to start nginx.service: Unit nginx.service is masked.To go back, sudo systemctl unmask nginx removes the link to /dev/null and makes the service startable again. A systemctl is-enabled nginx confirms that the masked state is gone. As long as the unit is masked, enable fails too, with exit code 1: Failed to enable unit: Unit /etc/systemd/system/nginx.service is masked.
Keep mask for services you want to forbid for good: cups.service on a server without a printer, a service replaced by another, a unit pulled in by a package you do not want. On a service that other units depend on, masking can make their start fail in a cascade at the next boot. In most cases, disable is enough.
mask has a limit that surprises: it mainly targets a unit shipped by a package, stored in /usr/lib/systemd/system/. For a unit you wrote yourself in /etc/systemd/system/, the link to /dev/null would take the place of your file, and systemctl refuses.
On a demo2.service unit written in /etc/systemd/system/, the command fails with an exit code of 1, on Debian 13 as on AlmaLinux 10:
sudo systemctl mask demo2; echo rc=$?Failed to mask unit: File '/etc/systemd/system/demo2.service' already existsrc=1To neutralize such a unit, disable --now stops it and removes it from boot; only deleting the file, followed by a daemon-reload, prevents any start.
The enabled-runtime state
systemctl enable --runtime enables a service without writing anything to disk: the symbolic link lands in /run/systemd/system/, an in-memory file system, emptied at every reboot.
sudo systemctl enable --runtime nginxsystemctl is-enabled nginxCreated symlink '/run/systemd/system/multi-user.target.wants/nginx.service' → '/usr/lib/systemd/system/nginx.service'.enabled-runtimeIt is useful for a temporary enabling during an intervention, when you want to get the original state back at reboot. It is a trap in the opposite case: enabled-runtime looks like enabled, yet the service will not come back after a reboot. For a lasting enabling, run sudo systemctl enable nginx again without --runtime.
Which target starts the service at boot?
A service does not start "at boot" in the absolute: it starts because a target reached during boot asks for it. The [Install] section of the unit file says which one, and it is what enable reads to know in which directory to put the link. Look at the last section of systemctl cat nginx.service:
systemctl cat nginx.service[Unit]Description=A high performance web server and a reverse proxy serverAfter=network-online.target remote-fs.target nss-lookup.targetWants=network-online.targetConditionFileIsExecutable=/usr/sbin/nginx
[Service]Type=forkingPIDFile=/run/nginx.pidExecStart=/usr/sbin/nginx -g 'daemon on; master_process on;'
[Install]WantedBy=multi-user.targetHere, WantedBy=multi-user.target creates the link in multi-user.target.wants/. It is a soft dependency: if the service fails, the target is still reached. RequiredBy= puts the same link as a hard dependency, where the failure of the service makes the target fail. Also= enables other units at the same time, without starting them, typically an associated socket, and works for disable too.
Targets replaced the SysV runlevels, and the old names survive as aliases: runlevel3.target points to multi-user.target, runlevel5.target to graphical.target, runlevel1.target to rescue.target.
| Target | Old runlevel | When it is reached |
|---|---|---|
multi-user.target | 3 | Networked server without a graphical interface, the normal case in production |
graphical.target | 5 | Workstation or server with a graphical environment |
rescue.target | 1 | Maintenance mode, a minimum of services, often single-user |
Almost all server services declare WantedBy=multi-user.target. They start even if the machine boots into graphical.target, because graphical.target declares Requires=multi-user.target. The target aimed at boot is read with systemctl get-default. To know what will be started, list the services hooked to the target:
systemctl list-dependencies multi-user.target --type=servicemulti-user.target nginx.service systemd-logind.service systemd-user-sessions.serviceFinally, in the output of systemctl list-unit-files --type=service, compare STATE and PRESET: an enabled in PRESET and a disabled in STATE point to a service that someone disabled on purpose, valuable information on a server you did not install.
Repair enabling with reenable and preset
Two commands help when the enabling no longer looks like what it should, typically after editing a unit file by hand. systemctl reenable removes then recreates the links from the current [Install] section. It is the reflex after a WantedBy= change: without it, the old link stays and the service remains hooked to the wrong target.
sudo systemctl reenable nginxRemoved '/etc/systemd/system/multi-user.target.wants/nginx.service'.Created symlink '/etc/systemd/system/multi-user.target.wants/nginx.service' → '/usr/lib/systemd/system/nginx.service'.systemctl preset nginx puts the service back in the state the distribution wants, that is, the PRESET column. Debian and Ubuntu enable most services when the package is installed, RHEL is much more conservative. The command says nothing when there is nothing to change, which often happens: check with systemctl is-enabled nginx.
Check that the service comes back after a reboot
is-enabled does not prove that the service will start. It proves that the intention to enable is recorded, that is, that the symbolic link exists in the right place. An enabled service can fail at boot because its configuration is broken, because it waits for a network mount that is missing, or because a dependency was masked. The check that counts is a real reboot, on a machine where you can afford it.
sudo rebootOn reconnecting, check the state of the service and the absence of failed units:
systemctl is-active nginxsystemctl --failedactiveAn empty output from systemctl --failed means no unit failed at boot. If the service is enabled but absent after the reboot, journalctl -b -u nginx shows the journal of the current boot for this unit, and the method continues in A service does not start: diagnosis method.
Create a service unit
Running an application as a systemd service brings what a plain nohup does not: automatic restart after a crash, start-up with the machine, and the program's messages gathered in the systemd journal. The unit file lives in /etc/systemd/system/, the directory reserved for the administrator, which takes precedence over the units shipped by packages.
A unit file reads as three blocks, and each one answers a question. [Unit] describes the service and its dependencies, [Service] says how to start the process, [Install] says when to enable it. The trap that follows: without an [Install] section, the service is static and systemctl enable will have no effect.
-
Create the unit file with the editor built into systemd, which handles the path and the permissions for you:
Terminal window sudo systemctl edit --full --force mon-app.service -
Describe the service, naming the unprivileged user that will run it. This user must exist on the machine, otherwise the start fails with
217/USER:[Unit]Description=Internal billing APIAfter=network-online.target postgresql.serviceWants=network-online.target[Service]Type=execUser=appuserGroup=appuserWorkingDirectory=/opt/mon-appExecStart=/opt/mon-app/bin/api --config /etc/mon-app/api.tomlExecReload=/bin/kill -HUP $MAINPIDRestart=on-failureRestartSec=5sNoNewPrivileges=true[Install]WantedBy=multi-user.target -
Enable and start the service.
systemctl editalready asked systemd to reread its configuration when the editor closed.daemon-reload, the command that requests this reread, remains necessary as soon as the file is written another way, by acpor a deployment tool:Terminal window sudo systemctl daemon-reload # useless after systemctl edit, mandatory after a cpsudo systemctl enable --now mon-app.service -
Check that the service stays up, letting a few seconds pass:
Terminal window sleep 3 && systemctl is-active mon-app.serviceThe output must show
active. If it showsfailed,journalctl -xeu mon-app.servicegives the reason.
In this example, After= only sets the start-up order: the application starts after the network and after PostgreSQL if it is started, but nothing forces PostgreSQL to start. Wants= additionally asks systemd to start network-online.target along with the service. If the application cannot run without PostgreSQL, add it to Wants= or Requires= as well.
Forgetting daemon-reload after changing a unit file without going through systemctl edit is a classic mistake: systemd keeps using the version it has in memory, and your changes seem to have no effect.
The three sections
A unit file always reads the same way, which lets you decipher an unknown unit without knowing it.
| Section | Role |
|---|---|
[Unit] | Description, dependencies (After=, Wants=, Requires=), start-up order |
[Service] | The type, the command, the user, the restart policy |
[Install] | What happens on enable: the target that will pull this service in at boot, multi-user.target for a server without a graphical interface |
Choose the right Type
The Type= directive tells systemd how to know that the service has started. A wrong choice produces false diagnoses, as the Type=simple trap below shows.
| Type | Behaviour | When to use it |
|---|---|---|
simple | The process started by ExecStart is the service; systemd considers it started as soon as it forks (creates the process) | The default when ExecStart= is set, to avoid in favour of exec |
exec | Like simple, but systemd waits for exec() to succeed (the call that replaces the created process with the program to run) | The right choice for a foreground binary (systemd 240 and later) |
forking | The process detaches, systemd follows the child process | Traditional daemons with a PIDFile= |
oneshot | Runs a command then ends | Maintenance scripts, one-off tasks |
notify | The service tells systemd it is ready through sd_notify() | Compatible applications, useful for start-up order |
idle | Waits for the other jobs to finish | Rare cases, console output |
The trap: Type=simple does not check that your binary exists
With Type=simple, systemd considers the service started as soon as it has created the process (the fork), so before it has even tried to execute the binary. The systemd.service(5) manual page says it: systemctl start reports success even if the service binary cannot be invoked. The command then returns with an exit code of 0, while the service is already dead.
What the state shows right after the start is therefore not reliable: in the example below, is-active still answers active, while the status of the demo unit, read 8 ms after start, already shows a failure. Only the exit code 0 of start is constant.
Two identical units differ only by this detail and behave in opposite ways. The first declares Type=simple, the second Type=exec, and both point to a binary that does not exist:
[Service]Type=simpleExecStart=/opt/demo/absentsystemctl start t-simple; echo "exit code of start = $?"; systemctl is-active t-simpleexit code of start = 0activeThe start is a success for the shell, and the service declares itself active. With Type=exec, systemd waits for the result of exec() and reports the failure:
systemctl start t-exec; echo "exit code of start = $?"; systemctl is-active t-execJob for t-exec.service failed because the control process exited with error code.See "systemctl status t-exec.service" and "journalctl -xeu t-exec.service" for details.exit code of start = 1failedThe consequence is concrete. A deployment script that tests $? after a systemctl start believes it succeeded while the application is dead, and the pipeline turns green. Here is the demo unit, whose ExecStart= targets /opt/demo/app.py, a missing file. The start returns 0, then the status read right away shows failed (Result: exit-code) with status=203/EXEC:
systemctl start demo; echo "exit code of start = $?"; systemctl status demoexit code of start = 0× demo.service - Demo qui echoue Loaded: loaded (/etc/systemd/system/demo.service; disabled; preset: enabled) Active: failed (Result: exit-code) since Fri 2026-11-13 15:07:52 UTC; 8ms ago Duration: 21ms Invocation: 37042dde29c34e189a699ef42fb390e0 Process: 5038 ExecStart=/opt/demo/app.py (code=exited, status=203/EXEC) Main PID: 5038 (code=exited, status=203/EXEC) Mem peak: 1.7M CPU: 3ms
Nov 13 15:07:52 lpg-debian.lab systemd[1]: Started demo.service - Demo qui echoue.Nov 13 15:07:52 lpg-debian.lab (app.py)[5038]: demo.service: Unable to locate executable '/opt/demo/app.py': No such file or directoryNov 13 15:07:52 lpg-debian.lab (app.py)[5038]: demo.service: Failed at step EXEC spawning /opt/demo/app.py: No such file or directoryNov 13 15:07:52 lpg-debian.lab systemd[1]: demo.service: Main process exited, code=exited, status=203/EXECNov 13 15:07:52 lpg-debian.lab systemd[1]: demo.service: Failed with result 'exit-code'.Look at the Active line and the Process line: the 203/EXEC code is written in this very first status, and the journal gives the cause (Unable to locate executable '/opt/demo/app.py': No such file or directory). The (app.py)[5038] prefix of the journal lines designates the child process created by systemd, which failed before it could start the program.
Restart automatically after a crash
A service that dies at three in the morning must get back up on its own. The Restart= directive handles this case, and the StartLimit* directives prevent the infinite restart loop that would hide a real problem.
| Directive | Value | Effect |
|---|---|---|
Restart | on-failure | Restarts if the exit code is non-zero, or after a signal, a timeout or the watchdog (the self-monitoring the service does on itself) |
Restart | always | Always restarts, except after an explicit systemctl stop |
Restart | no | Never restarts (the default) |
RestartSec | 5s | Waits 5 seconds between two attempts |
StartLimitBurst | 3 | [Unit] section: beyond 3 attempts in the window, systemd gives up |
StartLimitIntervalSec | 60s | [Unit] section: the window in which attempts are counted |
Restart=on-failure is the setting that the systemd.service(5) manual page recommends for a long-running service, and RestartSec=5s spaces out the attempts. Restart=always has a side effect: it also restarts a service whose configuration is broken, which fills the journal and delays the diagnosis.
The two StartLimit* directives live in [Unit]. On systemd 257, StartLimitBurst= placed in [Service] is nevertheless accepted (systemctl show returns the value written), whereas StartLimitIntervalSec= is ignored there. The daemon-reload reports nothing: systemd-analyze verify prints the message without running anything, with exit code 0.
/etc/systemd/system/demo-sl.service:6: Unknown key 'StartLimitIntervalSec' in section [Service], ignoring.Read the line number and the key name: the directive is misplaced and systemd does not apply it. Move it to [Unit]. The systemd 239 source code (RHEL 8) words this same message with the term Unknown lvalue.
Diagnose a failing service
When a service is in failed, the cause is usually written in the journal. You still have to read it in the right place (the page systemd journals presents journalctl in detail). This four-step method covers the common cases.
-
Read the status, which already shows the last lines of the journal:
Terminal window systemctl status mon-app.service -
Open the full journal of the unit, with the explanations of systemd:
Terminal window journalctl -xeu mon-app.serviceThe
-xoption adds contextual explanations,-ejumps to the end,-ufilters on the unit. -
Spot the failure code. On a service whose
ExecStart=points to a missing file, the journal is explicit:Output (Debian 13, systemd 257) Nov 13 15:05:45 lpg-debian.lab systemd[1]: demo.service: Main process exited, code=exited, status=203/EXECNov 13 15:05:45 lpg-debian.lab systemd[1]: demo.service: Failed with result 'exit-code'.The
203/EXECcode means that systemd could not start the executable: it is missing, not executable, or its path has a typo. Anls -lon the path ofExecStart=settles it in one second. -
Fix, reload, restart, in this order:
Terminal window sudo systemctl daemon-reloadsudo systemctl restart mon-app.servicesleep 3 && systemctl is-active mon-app.service
Four failure codes come up often in a journal. 203/EXEC signals an invalid path, 217/USER a User= that does not exist, 200/CHDIR a missing WorkingDirectory= and 226/NAMESPACE a hardening directive that is too strict. The systemd-analyze exit-status command lists the codes that systemd knows.
Harden an exposed service
A service reachable from the network should not be able to read /home, write to the file system or gain new privileges. For this, systemd provides isolation directives (sandboxing) that go into the [Service] section without changing the application. The following four directives make a starting point:
[Service]# forbids any privilege escalation (suid)NoNewPrivileges=true# the whole file system read-only, except the data directoryProtectSystem=strictReadWritePaths=/var/lib/mon-app# /home, /root and /run/user inaccessibleProtectHome=true# an isolated /tmp, invisible to other servicesPrivateTmp=trueThe comments sit on their own line, and this is not a matter of style: systemd accepts no end-of-line comment. Written NoNewPrivileges=true # forbids…, the directive is rejected then ignored, but the unit starts anyway, without the protection you think you set: systemctl show -p NoNewPrivileges returns no. On systemd 257 (Debian 13, AlmaLinux 10.2), systemd-analyze verify prints the error without running anything: run it before every daemon-reload.
/etc/systemd/system/demo-nnp.service:6: Failed to parse NoNewPrivileges=yes # commentaire, ignoring: Invalid argumentThe command systemd-analyze security mon-app.service rates the service from 0 to 10 (the lower the score, the better protected the service) and lists the missing protections one by one. To measure the effect of a directive, rate the service before, add the directive, then rate it after.
Best practices for enabling at boot
Enabling at boot is also an attack surface decision: every enabled service is a process that starts without anyone asking, often listening on the network.
- Use
enable --nowto put into service anddisable --nowto remove: forgetting one of the two halves is a common mistake. - Explicitly disable what the server does not need rather than letting the distribution preset decide, especially on Debian and Ubuntu, which enable almost everything at installation.
- Take stock of a server you inherit with
systemctl list-unit-files --state=enabled: it is the exact list of what will come back at the next reboot. - Test with a real reboot before going to production: a server that has never rebooted since its installation has a start-up behavior nobody knows.
- Automate the enabling in your configuration management tool rather than redoing it by hand on every machine.
Troubleshooting
The table pairs common symptoms with their cause and the action to take.
| Symptom | Probable cause | Solution |
|---|---|---|
systemctl start succeeds but the service is dead | Type=simple does not check exec() | Switch to Type=exec, or check with sleep 3 && systemctl is-active <service> |
Service failed with 203/EXEC | Missing binary, wrong path or not executable | ls -l on the path of ExecStart=, then chmod +x if needed |
The service does not appear in list-units | It is installed but never loaded | systemctl list-unit-files --type=service | grep <name> |
| A change to the unit file has no effect | systemd uses the version it has in memory | sudo systemctl daemon-reload then restart |
start answers Unit is masked | Service masked to /dev/null | sudo systemctl unmask <service> |
enable prints "The unit files have no installation config" and returns 0 | No [Install] section in the unit | Normal if the service is pulled in by a dependency; otherwise add [Install] and WantedBy= |
| A hardening directive has no effect | End-of-line comment, the directive is ignored | systemd-analyze verify <file>, comment on its own line |
mask answers already exists | The unit was written in /etc/systemd/system/ | disable --now, or delete the file: mask mainly targets package units |
| The service runs but disappears after a reboot | Never enabled at boot | sudo systemctl enable <service> then check is-enabled |
Permission denied in the journal | User= without rights on the files | Check the owner of the files and the hardening directives |
is-enabled answers enabled-runtime | Enabling done with --runtime, it lives in memory | Run sudo systemctl enable nginx again without --runtime |
Failed to enable unit: ... is masked | The service is masked | sudo systemctl unmask nginx then sudo systemctl enable --now nginx |
| No "Created symlink" on screen | Service already enabled (idempotent command) or package with a SysV script | Do not trust the message, settle it with systemctl is-enabled nginx |
| The service starts but not in the right boot context | WantedBy= points to the wrong target | Fix [Install] then sudo systemctl reenable nginx |
enabled but absent after a reboot | The enabling is right, the start-up is what fails | journalctl -b -u nginx to read the real error |
Practice
Writing a unit while reading a guide and making it stand on a real system are two different exercises. In a disposable virtual machine, you write a complete .service file, load it with daemon-reload, enable it with enable --now, then check its real state with is-active and the journal. The validation covers the final state: the service must be active, enabled at boot and do its job.
Key points
list-unitslists what is loaded in memory,list-unit-fileswhat is installed on disk: a service never started does not appear inlist-unitswithout--all(43 loaded units against 156 installed files on the demonstration server).- For an audit, the right command is
systemctl list-unit-files --type=service --state=enabled: it says what will start at the next boot. enabledandactiveare independent: one talks about the next boot, the other about now.- With
Type=simple,systemctl startreturns 0 even if the binary is missing, andis-activecan answeractiveright after the start. DeclareType=exec, or check the state a few seconds after the start. 203/EXECsignals an invalidExecStart=path or a non-executable file;journalctl -xeushows it.- After changing a unit file outside
systemctl edit,daemon-reloadis necessary, otherwise systemd keeps the version in memory. reloadrereads the configuration without cutting connections,restartstops the process: preferreloadwhen the unit declares anExecReload=.enablecreates a symbolic link in the target named byWantedBy=(multi-user.targetfor almost all server services),--nowadds thestart, and onlyis-enabledis authoritative: the message printed depends on the package.enabled-runtimelives in/runand does not survive a reboot;is-enabledalso returns0forstatic, so compare the printed string, not the exit code.is-enabledproves the intention to enable, not the success of the start-up: only a real reboot, followed bysystemctl --failed, counts.maskis stricter thandisable: it makes a package service impossible to start, even through a dependency. No end-of-line comment in a unit file, or the directive is ignored.
Knowledge check
Check that the essentials of this guide stuck. The questions cover only what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Master the Linux system logs with journalctl
A new full quiz with random questions
Work again only on the questions you missed
Frequently asked questions
Why systemd?
| Aspect | SysVinit (old) | systemd (modern) |
|---|---|---|
| Start-up | Sequential (slow) | Parallel (fast) |
| Dependencies | Manual scripts | Automatic |
| Logging | Scattered files | Centralised (journalctl) |
| Supervision | Cron/scripts | Built in (watchdog) |
| Isolation | Limited | cgroups, namespaces |
Main components
- systemctl: service management
- journalctl: reading the logs
- systemd-analyze: boot analysis
- Units: services, timers, sockets, targets...
Check that systemd is running
# Check PID 1
ps -p 1 -o comm=
# Must print: systemd
# Version
systemctl --version
Manage a service
# Start a service
sudo systemctl start nginx.service
# Stop a service
sudo systemctl stop nginx.service
# Restart (stop + start)
sudo systemctl restart nginx.service
# Reload the configuration (without stopping)
sudo systemctl reload nginx.service
# Check the state
systemctl status nginx.service
Automatic start-up
# Enable at boot
sudo systemctl enable nginx.service
# Disable at boot
sudo systemctl disable nginx.service
# Enable AND start right away
sudo systemctl enable --now nginx.service
List and search
# Services loaded in memory (not those never started)
systemctl list-units --type=service
# Every service installed on disk
systemctl list-unit-files --type=service
# Active services only
systemctl list-units --type=service --state=active
# Failed services
systemctl list-units --type=service --state=failed
# Search for a service
systemctl list-unit-files | grep docker
After changing a .service file
sudo systemctl daemon-reload
sudo systemctl restart mon-service.service
.service file in /etc/systemd/system/.Step 1: create the service file
sudo nano /etc/systemd/system/mon-app.service
Step 2: structure of the file
[Unit]
Description=My Python application
After=network.target
[Service]
Type=exec
User=www-data
Group=www-data
WorkingDirectory=/opt/mon-app
ExecStart=/opt/mon-app/venv/bin/python app.py
Restart=on-failure
RestartSec=5
# Security
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
Step 3: enable and start
# Reload the configuration
sudo systemctl daemon-reload
# Enable at boot
sudo systemctl enable mon-app.service
# Start
sudo systemctl start mon-app.service
# Check
systemctl status mon-app.service
Sections explained
| Section | Role |
|---|---|
| [Unit] | Metadata, description, dependencies |
| [Service] | How to run the service |
| [Install] | When to start (target) |
Comparison
| Command | Action | Immediate effect | At reboot |
|---|---|---|---|
start |
Starts the service | Yes | No |
stop |
Stops the service | Yes | No |
restart |
Stops then starts again | Yes | No |
reload |
Reloads the config | Yes (without interruption) | No |
enable |
Enables at boot | No | Yes |
disable |
Disables at boot | No | Yes |
Use cases
# I want to start a service now
sudo systemctl start nginx
# I want it to start automatically at boot
sudo systemctl enable nginx
# I want both at once
sudo systemctl enable --now nginx
# I changed the nginx config, I want to reload without cutting the service
sudo systemctl reload nginx
# The service crashed, I want to start it again
sudo systemctl restart nginx
Watch out
reload only works if the service supports it (nginx, Apache...). Otherwise, use restart.Step 1: check the state
systemctl status mon-service.service
Look for:Active: failed(red)- The exit code (
status=1/FAILURE) - The last log lines
Step 2: read the full logs
# Logs of the service
journalctl -u mon-service.service
# Recent logs only
journalctl -u mon-service.service -n 50
# Follow in real time
journalctl -u mon-service.service -f
# Errors only
journalctl -u mon-service.service -p err
Step 3: check the syntax of the service file
sudo systemd-analyze verify /etc/systemd/system/mon-service.service
Step 4: test by hand
# Run the ExecStart command by hand
sudo -u www-data /opt/mon-app/venv/bin/python app.py
Frequent errors
| Symptom | Probable cause |
|---|---|
code=exited, status=203/EXEC |
Invalid ExecStart path |
code=exited, status=217/USER |
User does not exist |
code=exited, status=200/CHDIR |
WorkingDirectory does not exist |
code=killed, signal=KILL |
OOM Killer (memory) |
Essential commands
# Logs of a specific service
journalctl -u nginx.service
# The last 100 lines
journalctl -u nginx.service -n 100
# Follow in real time (like tail -f)
journalctl -u nginx.service -f
# Since the last boot
journalctl -u nginx.service -b
# Since a date
journalctl -u nginx.service --since "2026-01-08 10:00"
# Between two dates
journalctl -u nginx.service --since yesterday --until today
Filter by severity
# Errors only
journalctl -u nginx.service -p err
# Errors and warnings
journalctl -u nginx.service -p warning
# Levels: emerg, alert, crit, err, warning, notice, info, debug
Output format
# JSON format (for parsing)
journalctl -u nginx.service -o json
# Short format (one line per entry)
journalctl -u nginx.service -o short
# With precise timestamps
journalctl -u nginx.service -o short-precise
Disk space management
# Size of the logs
journalctl --disk-usage
# Clean up (keep 7 days)
sudo journalctl --vacuum-time=7d
# Clean up (keep 500 MB max)
sudo journalctl --vacuum-size=500M
Common targets
| Target | Equivalent | Description |
|---|---|---|
poweroff.target |
runlevel 0 | System shutdown |
rescue.target |
runlevel 1 | Maintenance mode (single user) |
multi-user.target |
runlevel 3 | Multi-user mode (no GUI) |
graphical.target |
runlevel 5 | Graphical mode (with GUI) |
reboot.target |
runlevel 6 | Reboot |
Commands
# See the current target
systemctl get-default
# Change the default target (server without GUI)
sudo systemctl set-default multi-user.target
# Change the default target (desktop with GUI)
sudo systemctl set-default graphical.target
# Switch to a target right away
sudo systemctl isolate rescue.target
In a .service file
[Install]
WantedBy=multi-user.target
Means: "This service will be started when the system reaches multi-user mode."mask) is stricter than disabling it (disable).mask vs disable
| Action | Effect |
|---|---|
disable |
The service does not start automatically at boot, but can be started by hand |
mask |
The service is fully blocked, impossible to start even by hand |
Commands
# Mask a service
sudo systemctl mask dangerous-service.service
# Check (shows "masked")
systemctl status dangerous-service.service
# Try to start it (will fail)
sudo systemctl start dangerous-service.service
# Error: Unit dangerous-service.service is masked.
# Unmask
sudo systemctl unmask dangerous-service.service
Use cases
- Prevent a vulnerable service from starting by accident
- Turn off unwanted default services (cups, avahi...)
- Conflicts between incompatible services
How it works
mask creates a symbolic link to /dev/null, which makes the service unusable. That is why it only applies to a unit shipped by a package: for a unit you wrote in /etc/systemd/system/, the link would replace your file, and systemctl refuses with already exists.In the .service file
[Service]
# Memory limit (max 512 MB)
MemoryMax=512M
# Throttling beyond 400 MB
MemoryHigh=400M
# CPU limit (50% of one core)
CPUQuota=50%
# Maximum number of processes
TasksMax=100
# I/O weight (from 1 to 10000, 100 by default)
IOWeight=200
Apply temporarily (without changing the file)
# Limit memory to 256 MB
sudo systemctl set-property mon-service.service MemoryMax=256M
# Limit CPU to 25%
sudo systemctl set-property mon-service.service CPUQuota=25%
Check the current limits
systemctl show mon-service.service | grep -E 'Memory|CPU|Tasks'
Full example (greedy service)
[Service]
ExecStart=/opt/app/run.sh
# Strict limits
MemoryMax=1G
MemoryHigh=800M
# 2 cores at most
CPUQuota=200%
TasksMax=50
# If the kernel kills a process (OOM), stop the whole unit
OOMPolicy=kill
No end-of-line comment in a unit: MemoryHigh=400M # ... is rejected then ignored. systemd-analyze verify reports it.Recommended security options
[Service]
# Run as a non-root user
User=www-data
Group=www-data
# Prevent privilege escalation
NoNewPrivileges=true
# Read-only file system
ProtectSystem=strict
ProtectHome=true
# Private /tmp directory
PrivateTmp=true
# Kernel settings, modules and cgroups read-only or out of reach
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
# Filter system calls
SystemCallFilter=@system-service
SystemCallArchitectures=native
# Restricted network (if not needed)
PrivateNetwork=true
# Limited capabilities
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
Analyse the security of a service
# Security score (0-10, lower = better)
systemd-analyze security mon-service.service
Minimal secured example
[Unit]
Description=Secured API
After=network.target
[Service]
Type=exec
User=api-user
ExecStart=/opt/api/run
Restart=on-failure
# Hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/api
[Install]
WantedBy=multi-user.target
Total boot time
systemd-analyze
# Startup finished in 3.5s (kernel) + 12.4s (userspace) = 15.9s
Slowest services
systemd-analyze blame
# 8.123s apt-daily-upgrade.service
# 4.567s docker.service
# 2.345s NetworkManager-wait-online.service
# ...
Boot chart (SVG)
systemd-analyze plot > boot.svg
firefox boot.svg # View it
Critical chain (dependencies)
systemd-analyze critical-chain
# graphical.target @15.9s
# └─multi-user.target @15.9s
# └─docker.service @11.3s +4.5s
# └─network.target @11.2s
Common optimisations
| Slow service | Solution |
|---|---|
apt-daily-upgrade.service |
Shift it with a timer |
NetworkManager-wait-online |
Disable it if the IP is static |
docker.service |
Start on demand (socket) |
snapd.service |
Disable it if unused |
Configuration in the .service file
[Unit]
# At most 5 starts per minute, otherwise give up
StartLimitBurst=5
StartLimitIntervalSec=60
[Service]
ExecStart=/opt/app/run
# Restart on failure
Restart=on-failure
# Delay between two restarts
RestartSec=5
The StartLimit* directives go in [Unit]: put in [Service], StartLimitIntervalSec= is ignored with a warning.Restart options
| Value | Restarts if... |
|---|---|
no |
Never (default) |
on-success |
Exit code = 0 |
on-failure |
Code other than 0, signal, timeout |
on-abnormal |
Signal, timeout, watchdog |
on-abort |
Signal not caught by the program |
always |
Always (except systemctl stop) |
Robust example
[Unit]
# At most 3 starts in 5 minutes
StartLimitBurst=3
StartLimitIntervalSec=300
[Service]
ExecStart=/opt/api/server
Restart=always
RestartSec=10
# Watchdog: the program must signal it is alive every 30 s (sd_notify)
WatchdogSec=30
Check the behaviour
# Kill the process to test the restart
sudo kill -9 $(pgrep -f mon-app)
systemctl status mon-app.service
Create a timer
1. The service (what will run)# /etc/systemd/system/backup.service
[Unit]
Description=Daily backup
[Service]
Type=oneshot
ExecStart=/opt/scripts/backup.sh
User=backup
2. The timer (when to run)# /etc/systemd/system/backup.timer
[Unit]
Description=Timer for the daily backup
[Timer]
# Every day at 3 in the morning
OnCalendar=*-*-* 03:00:00
# Catch up if the system was off
Persistent=true
# Add a random delay (avoids simultaneous load)
RandomizedDelaySec=300
[Install]
WantedBy=timers.target
Enable the timer
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
OnCalendar syntax
# Every day at midnight
OnCalendar=daily
# Every hour
OnCalendar=hourly
# Every Monday at 8 am
OnCalendar=Mon *-*-* 08:00:00
# Every 15 minutes
OnCalendar=*:0/15
List the active timers
systemctl list-timers
Main types
| Type | Behaviour | Example |
|---|---|---|
simple |
The ExecStart process is the service, ready as soon as it forks | Historical default |
exec |
Like simple, but waits for exec() to succeed | The right choice for a foreground binary |
forking |
The process forks, the parent exits | Apache, traditional nginx |
oneshot |
Runs once and ends | Maintenance scripts |
notify |
The service signals when it is ready | dockerd |
dbus |
Ready when the D-Bus name is acquired | Desktop services |
idle |
Waits for the jobs to be finished | Login prompts |
Examples
exec (to prefer oversimple, which is the default): a missing binary makes systemctl start fail, where simple returns 0:[Service]
Type=exec
ExecStart=/usr/bin/node /opt/app/server.js
forking (traditional daemons):[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -HUP $MAINPID
oneshot (one-off scripts):[Service]
Type=oneshot
ExecStart=/opt/scripts/cleanup.sh
# Keep the "active" state after the script ends
RemainAfterExit=yes
notify (readiness signal):[Service]
Type=notify
ExecStart=/usr/bin/dockerd -H fd://
[Unit] section.Main directives
| Directive | Meaning |
|---|---|
After= |
Start after this service (order) |
Before= |
Start before this service |
Requires= |
Strong dependency: an explicit stop of the other stops this one; its failure at start-up only blocks this one with After= |
Wants= |
Weak dependency (if the other fails, go on) |
BindsTo= |
Very strong dependency: if the other stops or disappears, this one stops |
Conflicts= |
Cannot run at the same time |
Examples
API that needs the database:[Unit]
Description=My API
After=network.target postgresql.service
Requires=postgresql.service
# PostgreSQL starts before the API; if its start fails, the API does not start.
# A later crash of PostgreSQL does not stop the API: that would need BindsTo=.
Optional service (Redis as a cache):[Unit]
Description=My API with an optional cache
After=network.target redis.service
Wants=redis.service
# If Redis is not there, the API starts anyway
Incompatible services:[Unit]
Description=Apache
Conflicts=nginx.service
# Apache and nginx cannot run together
View the dependencies
# Dependencies of a service
systemctl list-dependencies nginx.service
# Reverse dependencies (who depends on...)
systemctl list-dependencies --reverse network.target