basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    OverviewLinuxsystemd

    Linux services and timers: how systemd works, daily commands, and what you can disable

    On most Linux distributions, background programs and scheduled jobs run under systemd — the PID 1 process that boots the system, supervises services, restricts their privileges, and collects their output in a single journal. One set of commands and text files manages daemons, schedules, sockets, memory limits, and system timers.

    What systemd, services, and timers are

    Once the Linux kernel finishes initializing hardware and mounts the root filesystem, it launches a single program with process ID PID 1. On Ubuntu, Debian, Fedora, Arch, RHEL, and most other modern distributions, that process is systemd. It brings up networking, mounts disks, starts SSH, Docker, and the rest of your background programs, and watches over them until shutdown.

    Everything systemd manages is defined as a unit — a short INI-style text file whose extension sets the unit type:

    .service

    Service

    background process or script

    Describes a program to run: binary path, user, environment variables, start order, and restart policy on failure. Examples: ssh.service, docker.service, nginx.service.

    .timer

    Timer

    schedule for a service

    Triggers a paired .service on a calendar schedule (say, 03:00 every night) or after a set delay from boot. Replaces cron and inherits every service feature: journal logging, dependencies, and sandboxing.

    .socket

    Socket

    on-demand activation

    Holds a network port or UNIX socket open itself and starts the linked .service only on the first connection. Saves memory for rarely used daemons; on Ubuntu 24.04, ssh.socket and docker.socket work this way.

    .target

    Target

    synchronization point

    Groups units into boot stages: network-online.target (network up), multi-user.target (normal server mode), graphical.target (desktop), timers.target (all enabled timers).

    .mount · .automount

    Mount

    disks and network shares

    Defines a mounted partition or NFS/SMB share. systemd converts /etc/fstab entries into .mount units at boot automatically.

    .path

    Path

    reacts to file changes

    Starts a linked .service when a watched file or directory appears, changes, or becomes non-empty — for instance, when a new file lands in an import folder.

    These units wire directly into each other. A timer runs nothing on its own — it triggers the service with the same name (or the one named in Unit=). A socket accepts a connection and hands it to the service. A target gathers related units into one start point:

    systemd (PID 1)
     ├── multi-user.target
     │    ├── ssh.socket ────────► ssh.service (starts on first connection)
     │    ├── docker.service ────► dockerd (long-running process, cgroup + journald)
     │    └── timers.target
     │         ├── fstrim.timer ────────► fstrim.service (weekly)
     │         └── backup.timer ────────► backup.service (Type=oneshot, at 03:00)
     └── network-online.target

    Why use systemd and what it gives you

    Before systemd, Linux systems ran SysVinit — sequential shell scripts in /etc/init.d/ — while scheduled jobs lived separately in cron. Getting automatic restarts, log rotation, and memory limits meant bolting on external wrappers (supervisord, flock, logrotate). systemd combines those pieces in one place:

    • One way to manage every service. Starting, stopping, checking status, and enabling at boot work the same way with systemctl for nginx, docker, crowdsec, and your own Python script, while all output lands in one journal (journalctl).
    • Exact process tracking via cgroups. Every service runs inside its own kernel control group (cgroup). When you run systemctl stop, systemd stops the main process and every child it spawned — no stray background processes left behind. The same cgroups enforce hard memory (MemoryMax=512M) and CPU (CPUQuota=50%) limits.
    • Restarts and failure alerts. Restart=on-failure brings a crashed process back after a pause (RestartSec=5). If the service exhausts its retries and enters failed, OnFailure= invokes a notifier unit and sends the tail of its journal (OnFailure= in systemd services).
    • Sandboxing without containers. Directives like ProtectSystem=strict, NoNewPrivileges=yes, CapabilityBoundingSet=, and IPAddressAllow= strip unneeded root capabilities and hide unrelated directories — without Docker (systemd sandbox, systemd-analyze security).
    • Timers instead of cron. A systemd timer prevents overlapping runs (while a oneshot service is still active, the next trigger is skipped), catches up on jobs missed during a reboot with Persistent=true, and sends output straight to journalctl. See systemd timers instead of cron for a full comparison with cron and a working example.
    • Parallel startup and explicit dependencies. Units start concurrently while waiting on the exact prerequisites listed in After= and Wants=/Requires= — such as networking or Docker.

    Where unit files live and how to edit them

    Unit files sit in three directories with strict precedence. When two directories contain a file with the same name, the higher row wins:

    Directory Priority Who writes there
    /etc/systemd/system/ highest administrator: custom units and overrides for system units
    /run/systemd/system/ middle runtime units in memory, gone after a reboot
    /usr/lib/systemd/system/ (and /lib/systemd/system/) base apt / dnf packages; overwritten on package upgrades

    Always put your own units in /etc/systemd/system/ — you can version them in git alongside the rest of your server configuration (Server configs in git).

    To inspect the full merged unit — the base file plus every .d/ drop-in — run systemctl cat <name>.service. If an override turns out to be unnecessary, remove it with sudo systemctl revert <name>.service, which deletes all custom overrides and restores the package’s original unit.

    Daily commands

    Commands that change service state require sudo; checking status and listing units work as a regular user.

    Command What it does
    systemctl status <name> service state, PID, memory usage, unit file path, and last 10 log lines
    sudo systemctl start|stop|restart <name> start, stop, or restart right now
    sudo systemctl reload <name> reload config without stopping the process (if supported)
    sudo systemctl enable --now <name> enable at boot and start immediately
    sudo systemctl disable --now <name> disable at boot and stop immediately
    sudo systemctl mask <name> block all starts (creates a symlink to /dev/null)
    sudo systemctl unmask <name> remove a mask
    sudo systemctl daemon-reload reload unit files from disk after manual edits
    systemctl --failed list only failed units
    systemctl list-units --type=service --state=running all currently running services
    systemctl list-timers --all all timers: last run, next run, and the service each activates
    systemctl cat <name> print the full unit file and all of its drop-in files
    sudo systemctl edit <name> create or open a drop-in file and run daemon-reload automatically
    journalctl -u <name> -b --no-pager full journal for the service since the last boot
    journalctl -u <name> -f follow new journal entries live
    journalctl -u <name> --since "1 hour ago" -p err errors only from the last hour

    Two companion utilities from the same suite: systemd-analyze blame shows how long each service took during boot, and systemd-analyze calendar --iterations=3 '<expression>' validates a timer schedule and prints the next three runs.

    Anatomy of a service and a timer

    Service types (Type=)

    Type= tells systemd when to consider a service started and move on to dependent units:

    Type How it behaves When to use it
    simple (default) process runs in the foreground; considered started right after launch most modern daemons, Python/Go/Node scripts
    exec like simple, but waits until the kernel runs the binary (execve) rather than returning after fork instead of simple, so bad paths and permission errors fail immediately
    oneshot runs a command and waits for it to exit; no start timeout by default timer jobs, setup scripts, staggered container startup (systemd)
    notify process sends a readiness signal over /run/systemd/notify daemons with sd_notify support (dockerd, crowdsec-firewall-bouncer)
    forking process forks into the background and the parent exits; needs PIDFile= legacy SysV-style daemons that cannot stay in the foreground

    An example of a long-running service — a Python web app or bot running under an unprivileged user with automatic restarts and a memory cap:

    /etc/systemd/system/bot.service
    [Unit]
    Description=Telegram monitoring bot
    After=network-online.target
    Wants=network-online.target

    The [Unit] section: description for systemctl status and start order. After= sets the order; Wants= pulls in networking softly.

    [Service]
    Type=exec
    User=example-user
    Group=example-user
    WorkingDirectory=/opt/bot
    EnvironmentFile=/opt/bot/.env
    ExecStart=/opt/bot/.venv/bin/python main.py
    Restart=on-failure
    RestartSec=5
    MemoryMax=256M
    Key part

    The workload: dedicated unprivileged user, working directory, environment file, start command, and restart-on-failure with a 5 s pause.

    [Install]
    WantedBy=multi-user.target

    [Install] is needed only for units you enable with systemctl enable. With multi-user.target, the service starts on a normal server boot.

    After creating the file, reload systemd and start the service:

    sudo systemctl daemon-reload
    sudo systemctl enable --now bot.service

    Two kinds of timers

    Timers come in two flavors — realtime (calendar) by clock/date, and monotonic by interval from an event:

    OnCalendar=

    Calendar

    hours, weekdays, dates

    Tied to wall-clock time (in the server’s time zone; check with timedatectl). Examples: daily, weekly, *-*-* 03:30:00 (every day at 03:30), Mon *-*-* 09:00 (Mondays at 09:00), *:0/15 (every 15 minutes). Only calendar timers support Persistent=true — catching up on a missed run after the server was powered off.

    OnBootSec= · OnUnitActiveSec=

    Monotonic

    interval from start

    Measure time from boot or from the last activation, unaffected by clock jumps or NTP adjustments. Example: OnBootSec=5min and OnUnitActiveSec=1h run the job 5 minutes after boot and then every hour after the previous run.

    A timer/service pair shares the same base name (cleanup.timer starts cleanup.service). Give the .service Type=oneshot, omit [Install] from the .service, and enable the .timer itself. See systemd timers instead of cron for a complete pair with Persistent=true, RandomizedDelaySec=, and schedule verification.

    User units (systemctl --user)

    Alongside the system instance, systemd runs a separate manager for each user. Its unit files live in ~/.config/systemd/user/, and commands run without sudo using --user:

    systemctl --user daemon-reload
    systemctl --user enable --now syncthing.service
    journalctl --user -u syncthing.service -n 20

    Use this for personal scripts, background sync, and workstation jobs: no root privileges needed, and configs stay inside your home directory. One caveat on servers — user services stop when your last SSH session closes. To start them at boot and keep them alive without a login, enable lingering once:

    sudo loginctl enable-linger example-user

    What runs by default on Ubuntu Server

    A fresh Ubuntu Server 24.04 install runs two to three dozen services and about a dozen system timers. List what is active on your machine with two commands:

    systemctl list-units --type=service --state=running
    systemctl list-timers --all

    Core system services — leave these alone

    These units keep the kernel, logging, networking, and server access running. Disabling any of them without a direct replacement breaks the host or locks you out of SSH:

    Unit What it does
    systemd-journald collects kernel and service logs; cap its size rather than disabling it (Swap, journal and time)
    systemd-udevd handles devices (disks, NICs, USB) and manages nodes under /dev
    systemd-logind manages user sessions, SSH logins, power state, and reboots
    dbus message bus between system services; parts of systemctl and networkd depend on it
    systemd-networkd or NetworkManager configures network interfaces (Ubuntu Server defaults to systemd-networkd via Netplan)
    systemd-resolved local DNS stub resolver on 127.0.0.53; disable only if you point /etc/resolv.conf at another DNS server manually
    systemd-timesyncd (or chrony) keeps the clock synced over NTP; inaccurate time breaks TLS certificates, TOTP, and logs
    ssh.socket / ssh.service remote SSH access
    ufw (or nftables) loads firewall rules at boot
    cron runs packaged scripts in /etc/cron.daily/ and /etc/cron.d/

    Built-in default timers

    Ubuntu moved much of its background maintenance and update work from cron to systemd timers. Most are useful and barely touch CPU or disk:

    Timer Frequency What it does
    apt-daily.timer twice a day runs apt update in the background to refresh package lists
    apt-daily-upgrade.timer daily (~06:00) installs security updates via unattended-upgrades (unattended-upgrades)
    dpkg-db-backup.timer daily backs up the installed-packages database /var/lib/dpkg/status to /var/backups/
    fstrim.timer weekly issues TRIM to SSDs or thin-provisioned hypervisor disks (Disk discard)
    logrotate.timer daily compresses and removes old text logs in /var/log/
    systemd-tmpfiles-clean.timer daily cleans expired temporary files according to tmpfiles.d rules
    e2scrub_all.timer weekly checks ext4 volumes on LVM online (exits immediately if there is no LVM)
    man-db.timer daily rebuilds the search index for man pages
    motd-news.timer twice a day fetches Ubuntu’s news banner shown on SSH login
    fwupd-refresh.timer twice a day refreshes the LVFS firmware metadata cache for physical hardware
    ua-timer.timer / esm-cache.service periodically checks Ubuntu Pro subscription status and ESM package cache

    Services and timers you can safely disable

    On a headless server without printers or Bluetooth, several default units sit idle — taking memory, holding open sockets, or spamming warnings into the journal. Before disabling a service, always check what depends on it:

    systemctl list-dependencies --reverse <name>.service
    Unit Why it is installed When you can disable it
    motd-news.timer pulls Ubuntu news into the SSH login banner almost always on any server
    ModemManager.service manages 3G/4G cellular modems on any VPS, VM, or home server without a USB modem
    multipathd.service and multipathd.socket manages multiple paths to a SAN disk on a regular server with local or virtual disks; often logs warnings about virtual disks
    fwupd.service and fwupd-refresh.timer BIOS/NVMe/USB firmware updates inside VPS instances and VMs where there is no physical hardware
    bluetooth.service Bluetooth stack on servers and VMs
    cups.service, cups.socket, cups-browsed.service printing and network printer discovery on any server without printers
    avahi-daemon.service and avahi-daemon.socket mDNS (.local hostnames on a LAN) on a public VPS; keep on a home network if you reach hosts via <name>.local
    udisks2.service desktop auto-mounting for USB drives on a headless server
    packagekit.service update backend for desktop software centers on servers managed with apt and unattended-upgrades
    apport.service crash-dump collector for Ubuntu bug reports on servers where you do not submit reports to Launchpad
    snapd.service, snapd.socket, snapd.seeded.service snap package manager only if snap list is empty or every tool you need comes from apt/Docker (some images ship lxd or certbot as snaps)

    How disable differs from mask

    Plain disable only removes the boot symlink under *.target.wants/. If a service has a .socket or another unit depends on it, it will start again.

    soft off

    disable --now

    Stops the service and removes it from boot. You can still start it manually (systemctl start), and a paired socket can still activate it. Good fit for motd-news.timer, ModemManager, and bluetooth.

    hard block

    mask

    Creates a symlink to /dev/null in /etc/systemd/system/. Neither a user, nor a socket, nor another unit, nor a package script can start it. Use for stubborn units like multipathd, or sleep.target on a laptop acting as a server so it never suspends. Undo with sudo systemctl unmask <name>.

    Disabling maintenance timers “just to save 5 MB of RAM” is counterproductive: systemd-tmpfiles-clean.timer, logrotate.timer, fstrim.timer, and dpkg-db-backup.timer run in fractions of a second and keep disks from filling up or SSDs from slowing down. The same goes for cloud-init: on a cloud VPS, avoid removing it until you know your provider does not rely on it for networking or SSH keys after an image rebuild — creating /etc/cloud/cloud-init.disabled is enough to stop it from running again.

    What to pick and when

    If you need to… Pick
    keep a background process running with auto-restart and logs .service with Type=exec (or simple) and Restart=on-failure
    run a scheduled script on a server with systemd a .service (Type=oneshot) + .timer with OnCalendar= (systemd timers instead of cron)
    avoid losing a nightly backup during a reboot Persistent=true in [Timer]
    tweak a setting on a packaged system service sudo systemctl edit <name>.service (drop-in in /etc/systemd/system/<name>.d/)
    run a personal service without root systemctl --user in ~/.config/systemd/user/ + loginctl enable-linger
    make sure an unwanted service never starts sudo systemctl disable --now (plus its .socket) or sudo systemctl mask
    schedule a job inside a minimal Docker container without systemd cron or supercronic in the container, or a host timer calling docker exec

    Trade-offs

    What you get

    • One tool for everything. Service startup, schedules, dependencies, memory caps, and logging follow one model and one CLI.
    • Direct diagnostics. systemctl status, systemctl --failed, and journalctl -u show exit codes, memory usage, and failure causes right away without hunting through scattered log files.
    • Built-in isolation. cgroup limits and systemd sandboxing restrict a service at the kernel level without installing Docker.
    • Clean overrides over packages. Drop-ins (.d/*.conf) keep your tweaks separate from distribution files and survive upgrades.

    What it costs

    • Two files per scheduled job. Each timer takes a .service and a .timer, where crontab needed a single line.
    • Sharp edges for newcomers. Forgotten daemon-reload, a minimal PATH with no HOME in services, and socket activation bringing a “disabled” daemon right back up.
    • Linux-with-systemd only. Alpine Linux (OpenRC), FreeBSD, macOS, and most Docker containers do not run systemd — unit files do not port directly.
    • Binary journal. You read journald logs with journalctl instead of grep on a text file, and without a cap in journald.conf the journal can grow to gigabytes (Swap, journal and time).

    Where to start

    1. Check what is already running and scheduled on your server:
    systemctl --failed
    systemctl list-units --type=service --state=running
    systemctl list-timers --all
    1. Check which services hold sockets and what depends on anything you plan to disable (systemctl list-dependencies --reverse <name>). On a standard VPS, start with harmless units like motd-news.timer and ModemManager.service.
    2. When you need your own scheduled script, build a .service + .timer pair in /etc/systemd/system/ using systemd timers instead of cron, add crash notifications for critical services with OnFailure= in systemd services, and lock down exposed daemons with systemd sandbox.

    If it doesn’t work

    Edited a .service or .timer file in /etc/systemd/system/, restarted the service, and it still runs with the old settings

    Cause
    systemd keeps unit definitions in memory and does not reread files from disk on its own. systemctl status shows a changed on disk warning.
    Fix
    Run sudo systemctl daemon-reload, then sudo systemctl restart <name>.service (or .timer).

    Disabled a service with systemctl disable --now, and a minute later it is active (running) again

    Cause
    The service has a paired .socket (socket activation), or another unit pulls it in as a dependency. A disabled .service still starts when something connects to its socket.
    Fix
    Check systemctl list-unit-files '<name>*' and systemctl list-dependencies --reverse <name>.service. Disable the paired .socket, or mask the unit to block all starts: sudo systemctl mask <name>.service.

    Created and enabled a timer, but it is missing from systemctl list-timers and the job never runs

    Cause
    You enabled the .service instead of the .timer, or left out the [Install] section with WantedBy=timers.target in the .timer file.
    Fix
    Add [Install] with WantedBy=timers.target to the .timer, run sudo systemctl daemon-reload && sudo systemctl enable --now <name>.timer, and confirm the row in systemctl list-timers --all.

    Edits to a system unit vanished after apt upgrade

    Cause
    You edited the package’s unit file in /usr/lib/systemd/system/ (or /lib/systemd/system/); the package manager overwrites that directory on upgrade.
    Fix
    Make changes through a drop-in in /etc/systemd/system/<name>.d/override.conf via sudo systemctl edit <name>.service — packages leave that directory alone.

    A user timer or service (systemctl --user) stops as soon as you disconnect from SSH

    Cause
    By default, systemd stops a user’s manager instance when their last active login session closes.
    Fix
    Enable lingering: sudo loginctl enable-linger example-user. User units then start at boot and keep running without an open session.

    A service failed, and systemctl status shows only a truncated error line without details

    Cause
    systemctl status prints the last 10 journal lines and clips long lines to the terminal width.
    Fix
    Read the full journal for this boot: journalctl -u <name>.service -b --no-pager, or grab the last 50 lines with -n 50.

    After disabling systemd-resolved, domain lookups fail and ping example.org returns Temporary failure in name resolution

    Cause
    /etc/resolv.conf is a symlink to /run/systemd/resolve/stub-resolv.conf, which points at local 127.0.0.53. With systemd-resolved stopped, nothing listens there.
    Fix
    Re-enable sudo systemctl enable --now systemd-resolved, or remove the /etc/resolv.conf symlink and write a regular file with your DNS servers by hand.