Linux systemd Tutorial: Services, Timers & Logs

Linux systemd Tutorial: Services, Timers, Targets and Logs

Every Linux server you will ever manage as a DevOps engineer runs systemd. It is the first process that starts when the machine boots, it is the process that starts your application, restarts it when it crashes, collects its logs, and schedules its recurring jobs. You can be a competent engineer without understanding systemd deeply, but you cannot be a fast one. The engineers who fix a failed service in two minutes are the ones who know systemctl, journalctl and unit files by heart.

This tutorial teaches systemd the practical way. You will learn what units and targets are, write a service unit for a real application, control it with systemctl, replace cron jobs with timers, read logs with journalctl, and harden a service so a compromised process cannot damage the host. The examples use Ubuntu 24.04, which ships systemd 255.4, but the commands are the same on Debian 13 (257.13), RHEL 10 (257) and other current distributions. Upstream systemd is at v262 as of September 2026, with 262.2 released on 5 November, but distributions freeze a version for years, so run systemctl --version before trusting any claim about a feature, including the claims in this article.

One important change to know about: systemd 258 removed cgroup v1 support entirely, so cgroup v2 is now always in use, and systemd 260 removed System V init script support. If you still have legacy init scripts on a host, they will not work on a current systemd. The migration path is to write a native unit file, which is exactly what this tutorial teaches you to do.

What systemd Is and How It Boots Your Machine

systemd is the init system, process ID 1, on almost every mainstream Linux distribution: Ubuntu, Debian, RHEL, Fedora, SUSE, Arch and Amazon Linux all use it. As PID 1, it is the first process the kernel starts, and it is the parent of every other process on the system. When you shut the machine down, systemd is the last process to exit. That position gives it enormous responsibility: starting services in the right order, watching them while they run, restarting them when they fail, and collecting their output.

It helps to think of systemd as a set of tools rather than one program. The core is the service manager, but the family includes journald for logging, logind for user sessions, networkd for networking, resolved for DNS, timesyncd for time synchronisation, and tmpfiles for managing temporary files. You will meet journald constantly in this tutorial and the others occasionally in passing. The important point is that they share a design philosophy: declarative configuration files, called units, that describe desired state instead of scripts that describe steps.

Everything systemd manages is a unit, named in the form name.type. The types you will meet every week are .service for a process, .socket for a listening socket that can start a service on demand, .timer for a schedule that starts a service, .target for a named group of units used as a synchronisation point, .mount for a filesystem mount, and .slice for a node in the cgroup tree that groups processes for resource control. Targets are the closest thing systemd has to the old runlevels: multi-user.target is the normal state of a server, and graphical.target adds a desktop on top of it.

Unit files live in three places, and the order matters. Distribution packages install units in /usr/lib/systemd/system. The administrator’s overrides and custom units go in /etc/systemd/system, which takes precedence. Per-user units live in ~/.config/systemd/user. The rule is simple: never edit a file in /usr/lib/systemd/system, because the next package update will overwrite your changes. Put your unit in /etc/systemd/system or add a drop-in override, which is a small file in a directory named after the unit, such as /etc/systemd/system/nginx.service.d/override.conf. Drop-ins are the clean way to change one setting of a packaged service without copying the whole file.

When you change a unit file, systemd does not notice automatically. You must run sudo systemctl daemon-reload to make it re-read the configuration. Forgetting this step is the single most common systemd mistake, and it produces a confusing symptom: you edit a file, restart the service, and nothing changes. If a change seems to have no effect, run daemon-reload first and ask questions later.

systemctl: Starting, Stopping and Inspecting Services

systemctl is the command you will use most, and it controls both the service manager and the units it manages. The verbs are few and consistent, which is what makes them easy to learn. Start, stop, restart, reload, enable, disable, status and is-active cover the large majority of daily work.

Command What it does When to use it
systemctl status nginx Shows whether the service is running, its process, recent log lines and whether it is enabled Your first check on any service; start here before anything else
systemctl start nginx Starts the service now, but not at boot Starting a service by hand after installing it
systemctl stop nginx Stops the service now Taking a service down for maintenance
systemctl restart nginx Stops and starts the service Applying a configuration change that needs a fresh process
systemctl reload nginx Asks the service to reload its configuration without stopping Configuration changes on services that support reload; no dropped connections
systemctl enable nginx Starts the service automatically at boot Making a service permanent; always do this for production services
systemctl enable --now nginx Enables at boot and starts immediately The one command you want when setting up a service
systemctl disable nginx Stops the service starting at boot Retiring a service without removing it
systemctl is-active nginx Prints active or inactive Scripts and health checks that need a yes or no answer
systemctl is-enabled nginx Prints enabled or disabled Auditing which services start at boot
systemctl list-units --type=service --state=failed Lists every failed service After a reboot or an incident, to find what did not come back
systemctl list-units --type=service --state=running Lists every running service Getting an overview of what a machine is doing
systemctl show nginx Dumps every property of the service Debugging a property you cannot find in the unit file
systemctl cat nginx Shows the unit file and its drop-ins Seeing the effective configuration, including overrides

Learn the difference between restart and reload, because using the wrong one causes real outages. Restart kills the process and starts a new one, which drops in-flight connections. Reload asks the running process to re-read its configuration, which most well-written daemons support without dropping anything. For nginx, systemctl reload nginx after a configuration change is the safe choice; restart is for when the binary itself changed or the process is wedged. A useful rule: if you changed a configuration file, try reload first. If the service does not support reload, systemctl will tell you, and then you restart.

The status output deserves a careful read. It shows the loaded state, the active state, the main process ID, the cgroup the service runs in, and the last few log lines. The exit code and the signal that killed a process are both shown here, and they often name the problem directly. A service that shows “failed (Result: exit-code)” with status 203 means the executable could not be found or could not be run, which usually points at a wrong path in ExecStart. A service that shows “failed (Result: timeout)” means it did not signal readiness within the timeout, which points at a slow start or a wrong Type setting. Read the status output before reaching for the logs; it narrows the search.

If you want a broader grounding in the Linux commands that surround systemctl, our Linux commands guide for DevOps engineers covers the essential toolkit.

Writing Your First Service Unit

A service unit is a small text file with three sections: Unit, Service and Install. The Unit section describes the service and its dependencies. The Service section describes how to run it. The Install section says when it should start. Here is a complete unit for a small Python web application, which you can adapt to almost any long-running process.

[Unit]
Description=My web application
Documentation=https://example.com/docs
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=appuser
Group=appuser
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/venv/bin/python /opt/myapp/app.py
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
StartLimitIntervalSec=60
StartLimitBurst=3
Environment=APP_ENV=production
EnvironmentFile=/etc/myapp/env
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

Walk through the choices. After=network-online.target with Wants=network-online.target means the service starts after the network is actually usable, not merely after the network service has started. That distinction matters: a service that binds to an address or calls an external API on startup will fail if the network is not ready.

Type=simple is the right default for most applications. It means the process started by ExecStart is the main process, and systemd considers the service started as soon as the process is running. The alternatives are forking for old daemons that fork into the background, oneshot for tasks that run and exit, and notify for services that tell systemd explicitly when they are ready. If you are unsure, use simple. Choosing forking for a process that does not fork is a classic error that leaves the service stuck in “activating” forever.

Restart=on-failure tells systemd to restart the process when it exits with a non-zero status or is killed by a signal, but not when it exits cleanly. That distinction is deliberate: a process that exits with status zero is saying it finished, and restarting it would loop forever. RestartSec=5 waits five seconds between restarts, and the StartLimit settings stop the loop entirely if the service fails three times in sixty seconds. Without a start limit, a broken service restarts forever, filling the disk with logs and hammering the CPU. With one, it fails, stays failed, and waits for a human. That is the correct behaviour: a service that cannot start is a problem to investigate, not a problem to hide with restarts.

User and Group run the process as an unprivileged user. Never run an application as root when you can avoid it. Create a dedicated user with no login shell and no home directory, give it ownership of only the files it needs, and let systemd drop privileges before starting the process. If the application is compromised, the attacker gets the permissions of that user, which should be as close to nothing as possible.

To install the unit, save it as /etc/systemd/system/myapp.service, then run sudo systemctl daemon-reload, sudo systemctl enable --now myapp, and sudo systemctl status myapp to confirm it is running. If it fails, the status output and journalctl -u myapp will tell you why. Common first-time errors are a wrong path in ExecStart, a missing WorkingDirectory, and environment variables that exist in your shell but not in the unit.

Timers: Replacing Cron the systemd Way

Cron has scheduled jobs on Unix for decades, and it still works. But systemd timers are better for most DevOps work, for three concrete reasons. First, a timer is a unit, which means it has logging, status and failure handling built in, and you can see its history with the same tools you use for services. Second, a timer can run a job that was missed while the machine was off, which cron cannot do. Third, a timer can express schedules cron cannot, such as running a job a fixed time after boot, or with a randomised delay so a hundred machines do not hit a server at the same second.

A timer always works in pairs: a .timer unit that defines the schedule, and a .service unit that defines what runs. Here is a timer that runs a backup script every night at 2 a.m., with the matching service.

# /etc/systemd/system/backup.timer
[Unit]
Description=Run nightly backup

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
RandomizedDelaySec=600

[Install]
WantedBy=timers.target
# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup job

[Service]
Type=oneshot
User=backup
ExecStart=/usr/local/bin/backup.sh

The OnCalendar setting uses a calendar expression. *-*-* 02:00:00 means every day at 2 a.m. Other useful expressions are Mon *-*-* 03:00:00 for Mondays at 3 a.m., *-*-* *:00:00 for every hour on the hour, and *-*-01 00:00:00 for the first of every month. You can also use monotonic timers: OnBootSec=15min runs fifteen minutes after boot, and OnUnitActiveSec=1h runs one hour after the last run finished. Monotonic timers are ideal for maintenance tasks that should run regularly but do not need a specific clock time.

Persistent=true is the setting that makes timers better than cron for machines that are not always on. If the machine was off at 2 a.m., a persistent timer runs the job as soon as the machine boots. RandomizedDelaySec=600 spreads the start time by up to ten minutes, which prevents a fleet of machines from all starting a heavy job at the same instant. Both settings cost nothing and prevent real problems.

Manage timers with the same systemctl verbs you already know, plus one extra command to see them all.

sudo systemctl enable --now backup.timer
systemctl list-timers --all
systemctl status backup.timer
sudo systemctl start backup.service   # run the job now, outside its schedule
journalctl -u backup.service          # see the last run's output

Note that enabling the timer is what matters, not enabling the service. The service is started by the timer, and enabling the service would run it at boot, which is not what you want for a nightly job. A common mistake is enabling both and then wondering why the backup ran at boot. Enable the timer, leave the service disabled, and start the service by hand when you want a run outside the schedule.

When should you keep cron? When the job is trivial, the machine already uses cron for other jobs, and nobody needs logging or failure alerts for it. But the moment a scheduled job matters, when a missed backup or a failed cleanup has consequences, a timer is the better tool. It logs to the journal, it shows up in systemctl status, and it can notify you when it fails.

journalctl: Reading Logs That Actually Help

journald collects the output of every service managed by systemd and stores it in a structured, indexed journal. journalctl is the tool for reading it, and it is dramatically more powerful than reading text files, because every log line carries metadata: the unit that produced it, the priority, the timestamp with microsecond precision, and the boot it belongs to.

Command What it does When to use it
journalctl -u nginx Shows logs for one unit Debugging a specific service
journalctl -u nginx -f Follows logs live Watching a service while you reproduce a problem
journalctl -u nginx --since "1 hour ago" Shows logs from the last hour Cutting through old noise to the recent problem
journalctl -u nginx --since today Shows today’s logs Reviewing what happened since midnight
journalctl -b Shows logs from the current boot only After a reboot, to see what happened since startup
journalctl -b -1 Shows logs from the previous boot Investigating a crash that took the machine down
journalctl -p err Shows only errors and worse Finding problems without reading informational noise
journalctl -u nginx -o json-pretty Shows logs as structured JSON Shipping logs to a collector or parsing them in a script
journalctl --disk-usage Shows how much disk the journal uses When disk space is disappearing
journalctl --vacuum-size=500M Deletes old journal data down to 500 MB Reclaiming disk in an emergency
journalctl -u nginx --no-pager Prints logs without opening a pager Scripts and piping output to grep

The flags combine freely, and the combinations are where the power is. journalctl -u myapp -f --since "10 minutes ago" follows a service’s recent logs live. journalctl -b -p err shows every error since the machine booted, which is the fastest way to find out what went wrong after a bad reboot. journalctl -u myapp -o json-pretty --since today | grep -i timeout finds every timeout in today’s structured logs.

Two things catch people out with journald. The first is persistence. On many distributions, the journal is stored in memory by default and lost on reboot, because the directory /var/log/journal does not exist. Create that directory and restart journald, or set Storage=persistent in /etc/systemd/journald.conf, and logs survive reboots. Do this on every server you care about: logs from the previous boot are exactly the logs you need after a crash, and they are gone forever if the journal was not persistent.

The second is disk usage. The journal grows without limit until it hits its configured cap, and on a busy machine that cap arrives faster than you expect. Check journalctl --disk-usage regularly and set SystemMaxUse in journald.conf to a sensible value for the machine.

Targets, Dependencies and Troubleshooting Failed Services

Targets group units and define the state of the machine. multi-user.target is the normal server state. network-online.target means the network is usable. timers.target is the target that timers attach to. You rarely need to create a target, but you need to understand them to read unit files and to debug boot ordering.

Dependencies are declared with a small set of directives, and confusing them causes most boot-order bugs. Wants says start this unit too, but do not fail if it fails. Requires says start this unit, and fail if it fails. After says start this unit after that one, but says nothing about whether it should start at all. The classic mistake is writing After=postgresql.service without Requires or Wants: the service starts after PostgreSQL when PostgreSQL happens to start, but nothing guarantees PostgreSQL starts. If your service needs the database, declare both: After=postgresql.service and Requires=postgresql.service. If it merely benefits from the database being available, use Wants instead of Requires, so a database failure does not take your service down with it.

When a service fails, work through a fixed sequence. First, systemctl status and read the active state, the exit code and the last log lines. Second, journalctl -u SERVICE --since "30 minutes ago" for the full story. Third, systemctl cat SERVICE to see the effective unit file, including drop-ins you may have forgotten. Fourth, check the obvious: does the executable path exist, does the user exist, does the working directory exist, and are the permissions right? Most failures are one of these, and the sequence finds them in minutes.

Some failures have specific signatures worth memorising. Exit code 203 means the executable could not be run, usually a wrong ExecStart path. Exit code 200 means a missing directory in a path directive. A service stuck in “activating” usually means the wrong Type: a simple service that forks, or a forking service that does not. A service that starts by hand but fails at boot usually means a missing After dependency, most often the network. A service that fails only sometimes usually means a race with another service, and the fix is a dependency declaration, not a sleep in a wrapper script. If you write automation around services, our bash scripting guide for DevOps shows how to check service state from scripts safely.

Hardening Services and Limiting Resources

systemd can sandbox a service with a few lines, and this is one of the most valuable things it does for security. The directives below restrict what a compromised process can do, and they cost almost nothing to add. Not every directive works for every service, so add them one at a time and test, but a service that runs with these restrictions is dramatically harder to exploit than one that does not.

[Service]
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
NoNewPrivileges=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectControlGroups=true
ReadWritePaths=/var/lib/myapp
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
MemoryMax=512M
CPUQuota=50%
TasksMax=100

PrivateTmp=true gives the service its own temporary directory, so it cannot see or interfere with other processes’ temporary files. ProtectSystem=strict mounts the whole filesystem read-only except for the paths you explicitly allow with ReadWritePaths. NoNewPrivileges=true prevents the process from gaining new privileges, which blocks a whole class of privilege escalation. Together these turn a compromised application into a process trapped in a small box with nothing useful to attack.

Resource limits use cgroup v2, which is now the only cgroup version systemd supports. MemoryMax=512M kills the process if it exceeds 512 MB of memory, which prevents a memory leak in one service from taking down the whole machine. CPUQuota=50% limits the service to half a CPU. TasksMax=100 limits the number of threads and processes it can create, which blocks fork bombs. Set these limits based on what the service actually needs: watch the service under load, find its real usage, and set the limit a little above it.

Use systemd-analyze security SERVICE to audit a service. It scores the unit against a checklist of hardening options and reports an exposure level, with suggestions for what to add. Run it on every service you write, and treat a high exposure score the way you would treat a failing test: fix it before shipping. The systemd.service man page documents every directive, and the systemctl man page documents every command in this tutorial. When a directive behaves in a way you did not expect, the man page is the authority, not a blog post.

Frequently Asked Questions

What is the difference between systemctl and service? The service command is a compatibility wrapper from the old SysV init era that forwards to systemctl on systemd machines. systemctl is the native tool and the one you should learn: it exposes everything systemd can do, while service only covers the basics. The old wrapper still works, but it hides the features that make systemd worth using.

Why does my service fail at boot but work when I start it manually? Almost always a missing dependency. The usual cause is the network: the service needs network-online.target but only declares network.target, or declares neither. Another common cause is a dependency on a mounted filesystem that is not ready yet. Check the journal for the boot in question with journalctl -b and look at the first error; it usually names the missing resource directly.

Should I use systemd timers or cron? Use timers when the job matters: when a missed run has consequences, when you need logging and failure alerts, or when you want the job to run after a missed schedule. Use cron for trivial jobs on machines that already use it. Timers are units, so they get status, logging and failure handling for free, which is why they are the better default for production work.

How do I see logs from the previous boot? Run journalctl -b -1 to see the previous boot, or journalctl –list-boots to see all recorded boots and pick one. This only works if the journal is persistent, which requires the directory /var/log/journal to exist or Storage=persistent in journald.conf. Set that up before you need it, because logs from a crashed boot cannot be recovered afterwards.

Can I run systemd services as a normal user? Yes. User services live in ~/.config/systemd/user and are managed with systemctl –user. They run with your permissions, start when you log in by default, and can be made to start at boot with loginctl enable-linger. User services are ideal for development tools and personal daemons that do not need root, and they keep system services clean.

Conclusion

systemd is not glamorous, but it is the foundation every Linux service stands on. Learn systemctl until the verbs are automatic, write unit files instead of wrapper scripts, use timers for jobs that matter, and read the journal before guessing. The habits in this tutorial, declaring dependencies explicitly, setting restart limits, running as an unprivileged user, hardening with sandbox directives, are small individually and transformative together. The next step is to take a service you currently start by hand or from a script and convert it to a unit file. If you want to go deeper into Linux for operations work, our Linux for DevOps engineers guide covers the wider toolkit this tutorial builds on.

Sources: Verified 2 Dec 2026. systemd.service man page: https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html ; systemctl man page: https://www.freedesktop.org/software/systemd/man/latest/systemctl.html . systemd v262 upstream (22 Sep 2026, 262.2 on 5 Nov); distro versions per release trackers — re-check your distro’s version with systemctl –version before relying on a feature. No unverified figures stated.

Scroll to Top