# Services with systemd: run, restart, read the logs

Start, stop, enable and inspect services with systemctl, find out why one failed with journalctl, and turn your own app into a service that starts at boot and restarts when it crashes.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 9. About 35 minutes, beginner. Source: https://devops.rajeev.pro/courses/linux/09-services-with-systemd

## What you will learn

- Read systemctl status and explain loaded, enabled, active and the main PID
- Tell start from enable, and restart from reload
- Find why a service failed with journalctl, filtered by unit, time and priority
- Write a unit file for your own app with a user, restart policy and environment
- Change a packaged service safely with an override instead of editing its file
- Schedule a job with a systemd timer, and know when cron is the simpler choice

## What systemd does

**The problem.** You've deployed your app to a server and started it from your SSH session. Then
three things happen. You close the laptop, the SSH session ends, and the app dies with it. You
restart it with `nohup` so it survives the logout, and at 3 a.m. it crashes on a bad request and
stays down until someone notices. Next week the server reboots for a kernel update, and nothing
starts the app again at all. Each fix is another hack: a `nohup` here, a restart loop in a shell
script there, a line in some startup file nobody remembers.

**What systemd changes.** Instead of starting programs by hand, you describe them once in a small
file: what to run, as which user, what to do if it crashes, and whether to start it at boot.
systemd reads those files and does the babysitting: it starts services in the right order at
boot, restarts them when they crash, collects everything they print, and lets you check on them
with one command.

**How it works.** On almost every modern Linux server, **systemd** is PID 1: the first process, which starts and
looks after everything else. Each thing it manages is a **unit**, described by a small text file.
The ones you'll use most are **services** (`nginx.service`, `ssh.service`), **timers** (scheduled
jobs) and **targets** (groups of units, like "everything needed for a multi-user server").

You talk to systemd with `systemctl`, and read what services printed with `journalctl`.

In this lesson you'll read a service's status, start and enable services, find out why one failed,
turn your own app into a proper service, and run jobs on a schedule.

## Reading systemctl status

When an application is unavailable, first determine whether systemd considers its service loaded, running,
failed or stopped. `systemctl status` combines unit configuration, active state, main process details and
recent journal messages in one view. It is a summary, not a full diagnostic; follow the journal for more
context.

```sh
$ 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 Tue 2026-10-13 09:12:04 IST; 2h 9min ago
       Docs: man:nginx(8)
   Main PID: 812 (nginx)
      Tasks: 3 (limit: 4532)
     Memory: 5.1M (peak: 6.0M)
     CGroup: /system.slice/nginx.service
             ├─812 "nginx: master process /usr/sbin/nginx"
             └─813 "nginx: worker process"

Oct 13 09:12:04 web-01 systemd[1]: Started nginx.service - A high performance web server…
```

| Line         | Tells you                                                                           |
| ------------ | ----------------------------------------------------------------------------------- |
| **Loaded**   | which unit file is used, and **enabled** (starts at boot) or **disabled**           |
| **Active**   | **active (running)**, **inactive (dead)** (stopped), or **failed**, plus since when |
| **Main PID** | the process systemd watches; the CGroup lists all its processes                     |
| last lines   | the newest log lines from this service                                              |

The dot at the start is green when running and red when failed. `systemctl is-active nginx` and
`systemctl is-enabled nginx` answer with one word, which is handy in scripts.

Use `is-active` to test the current runtime state and `is-enabled` to see whether the unit is configured to
start at boot. These are separate questions: a disabled unit can be running now, and an enabled unit can be
stopped now. A common mistake is seeing "enabled" and assuming the service is healthy; check active state and
whether the application actually answers requests.

## Start, stop, enable and reload

```sh
$ sudo systemctl start nginx        # run it now
$ sudo systemctl stop nginx         # stop it now
$ sudo systemctl restart nginx      # stop, then start: a short outage
$ sudo systemctl reload nginx       # re-read the config without stopping (if supported)
$ sudo systemctl enable nginx       # start at every boot (doesn't start it now)
$ sudo systemctl enable --now nginx # both: now and at every boot
$ sudo systemctl disable nginx      # don't start at boot
$ systemctl --failed                # every unit that has failed
$ systemctl list-units --type=service --state=running
```

> **Figure.** A systemd unit file for an app, with its three sections explained. [Unit] describes the service and its order: After=network-online.target. [Service] says how to run it: User=myapp, WorkingDirectory, EnvironmentFile, ExecStart with the full command, Restart=on-failure and RestartSec=5. [Install] says when to start it: WantedBy=multi-user.target, which systemctl enable turns into a link. On the right: start runs it now, enable makes it start at boot, and daemon-reload is needed after every edit.
>
> Three sections: what it is, how to run it, when to start it.

**Enabled** and **running** are independent. A service can run without being enabled (gone after
a reboot) or be enabled while stopped (starts at the next boot). Check both after every change.

Prefer **reload** when the service supports it: nginx and sshd re-read their config and keep
existing connections. `restart` drops them. And always validate first (`nginx -t`, `sshd -t`), as
in the _Editing files_ lesson.

> **Video.** [Systemd Explained: How to Manage Linux Services Easily](https://www.youtube.com/watch?v=Kzpm-rGAXos) (Learn Linux TV)

## Why did it fail? journalctl

When systemd reports a failed unit, its journal contains messages from the service and supervisor. Filter by
unit, time or boot so you can focus on the relevant event instead of reading the whole system log.

```sh
$ systemctl status myapp                       # the last ~10 lines, often enough
$ sudo journalctl -u myapp -n 50               # the last 50 lines from this unit
$ sudo journalctl -u myapp -f                  # follow live while you restart it
$ sudo journalctl -u myapp --since "10 min ago"
$ sudo journalctl -u myapp -b                  # only since the last boot
$ sudo journalctl -p err -b                    # errors from everything since boot
$ sudo journalctl -u myapp -o cat              # just the messages, no timestamps
```

The usual reasons a service fails, and what the journal says:

| Journal says                         | Usually means                                                                                             |
| ------------------------------------ | --------------------------------------------------------------------------------------------------------- |
| `status=203/EXEC`                    | the `ExecStart` path is wrong or the file isn't executable                                                |
| `status=217/USER`                    | the `User=` account doesn't exist                                                                         |
| `Address already in use`             | another process is on that port: `sudo ss -tlnp`                                                          |
| `Permission denied` on a file        | the service's user can't read it: check owner and mode                                                    |
| `Start request repeated too quickly` | it crashed several times in a row and systemd gave up: fix the cause, then `systemctl reset-failed myapp` |

On many servers the journal is kept in memory and lost at reboot. To keep it, make sure
`/var/log/journal/` exists (`sudo mkdir -p /var/log/journal && sudo systemctl restart
systemd-journald`). `journalctl --disk-usage` and `sudo journalctl --vacuum-time=14d` keep its size
in check.

Use `-u` for one unit, `--since` for a time window, and `-b` to select the current boot. Check the service
logs before restarting repeatedly; repeated failures can obscure the first cause. A common mistake is
searching only today's logs after a reboot when the failure happened during the previous boot.

> **Video.** [journalctl Basics: How to Easily Check Your Linux Logs](https://www.youtube.com/watch?v=0dG3vUYt7Uk) (Learn Linux TV)

## Your own service: a unit file

Running your app with `nohup` or inside `tmux` works until the server reboots or the app crashes.
A unit file fixes both:

```ini
# /etc/systemd/system/myapp.service
[Unit]
Description=My web app
After=network-online.target
Wants=network-online.target

[Service]
User=myapp
WorkingDirectory=/srv/myapp
EnvironmentFile=/etc/myapp/myapp.env
ExecStart=/usr/bin/python3 -m http.server 8080
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
```

```sh
$ sudo systemctl daemon-reload            # after creating or editing any unit file
$ sudo systemctl enable --now myapp
$ systemctl status myapp
```

The details that matter:

- **`User=`** runs it as the service account from the _Users and groups_ lesson, never as root.
- **`ExecStart=`** needs the **full path** to the program. systemd doesn't use your shell's `PATH`,
  and doesn't run a shell: write `ExecStart=/bin/bash -c '…'` if you need pipes or `&&`.
- **`EnvironmentFile=`** keeps settings and secrets out of the unit file (`chmod 600` it).
- **`Restart=on-failure`** brings the app back after a crash or a kill, but not after you stop it.
- **`WantedBy=multi-user.target`** is what `enable` hooks into: "start this with the normal server".

> **Figure.** Animated. myapp is active (running) with PID 3010. sudo kill -9 3010 kills it and the status turns to failed. Because of Restart=on-failure and RestartSec=5, systemd waits five seconds in activating (auto-restart), then starts it again as PID 3077, and NRestarts goes from 0 to 1. sudo systemctl stop myapp then stops it on purpose: inactive (dead), with no restart.
>
> A crash brings the service back after RestartSec, with a new PID. systemctl stop is deliberate, so it stays stopped.

## Changing a packaged service: overrides

Say nginx needs to handle more open connections, so you want to raise its file limit. The obvious
move is to open its unit file and add a line. It works until the next `apt upgrade`, when the
package quietly replaces the file and your change disappears. Nobody notices until the next
traffic spike.

Never edit the files in `/usr/lib/systemd/system/`: they belong to the package and are replaced on
the next upgrade. Add an **override** instead:

```sh
$ sudo systemctl edit nginx
```

```ini
# opens /etc/systemd/system/nginx.service.d/override.conf
[Service]
LimitNOFILE=65535
Restart=on-failure
```

```sh
$ systemctl cat nginx          # the package's file plus your override, as systemd sees them
$ sudo systemctl restart nginx
```

`systemctl edit` runs `daemon-reload` for you. Files in `/etc/systemd/system/` always win over
`/usr/lib/systemd/system/`.

Use an override for local service settings such as limits or restart behavior. Inspect the merged definition
with `systemctl cat`, then restart or reload the service if the setting requires it. Keep changes small so
package updates can still provide safe defaults. A common mistake is replacing the whole vendor unit when a
drop-in override would change only one setting.

## Scheduled jobs: timers and cron

Backups, log clean-ups, certificate renewals and reports all need to run on their own, on a
schedule, without anyone logged in. Linux has two ways to do that.

`crontab -e` is still the quickest:

```text
# m  h  dom mon dow  command
30   2  *   *   *    /srv/scripts/backup.sh >> /var/log/backup.log 2>&1
```

Read the five fields left to right: minute 30, hour 2, any day of the month, any month, any day of
the week. In other words, 02:30 every day. A `*` means "every". `0 */6 * * *` is every 6 hours,
and `0 9 * * 1-5` is 9:00 on weekdays. Cron runs the command with a very small environment, so
always use full paths, and send the output to a file (`>> … 2>&1`) or you'll never see the errors.

systemd **timers** do the same job with more control: logs in the journal, no overlap if the last
run hasn't finished, and catch-up runs after downtime (`Persistent=true`). A timer starts a
service of the same name:

```ini
# /etc/systemd/system/backup.timer      (runs backup.service)
[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true

[Install]
WantedBy=timers.target
```

```sh
$ sudo systemctl enable --now backup.timer
$ systemctl list-timers            # every timer, with its next and last run
```

**Cron or a timer?** Cron is fine for simple jobs on a single server. Use a timer when it matters
that the job really ran: you can check it with `systemctl status backup.service` and read its
output in `journalctl -u backup`, a slow run never overlaps with the next one, and a run missed
because the server was off happens as soon as it's back up. (Plain cron doesn't do that: a run missed while the
server was off is simply skipped until the next scheduled time.)

> **In production.** After changing any service, check three things: `systemctl is-active`, `systemctl is-enabled`, and that it actually answers (`curl`, a login, a query). A service can be "active (running)" while it's broken inside, which is why health checks test the real thing.

> **Video.** [Automate Your Tasks with systemd Timers: A Step-by-Step Guide](https://www.youtube.com/watch?v=n6BuUgkZ5T0) (Learn Linux TV)

## Mission: Make an app survive crashes and reboots

A small web app is started by hand with nohup and dies every time the server reboots. Turn it into a service that runs as its own user, starts at boot, and restarts by itself if it crashes. Then prove the restart works.

- You need: A server where you have sudo, with python3
- You'll have: /etc/systemd/system/myapp.service

```sh
$ sudo useradd --system --no-create-home --shell /usr/sbin/nologin myapp
$ sudo mkdir -p /srv/myapp && echo "hello from myapp" | sudo tee /srv/myapp/index.html > /dev/null
$ sudo tee /etc/systemd/system/myapp.service > /dev/null <<'EOF'
[Unit]
Description=My web app
After=network-online.target

[Service]
User=myapp
WorkingDirectory=/srv/myapp
ExecStart=/usr/bin/python3 -m http.server 8080
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target
EOF
$ sudo systemctl daemon-reload && sudo systemctl enable --now myapp
$ curl -s localhost:8080
hello from myapp
$ sudo kill -9 "$(systemctl show -p MainPID --value myapp)"   # simulate a crash
$ sleep 3; systemctl show -p NRestarts --value myapp
1
$ curl -s localhost:8080
hello from myapp
```

`NRestarts=1` is systemd telling you it noticed the crash and brought the app back, with nobody
paged. `enable` means the same happens after a reboot. Clean up with `sudo systemctl disable
--now myapp`.

## Try it

- Run `systemctl status cron` (or `ssh`) and point at the Loaded, Active and Main PID lines.
- List failed units with `systemctl --failed`, and running services with `systemctl list-units --type=service`.
- Show the last 20 log lines of a service with `journalctl -u cron -n 20`, then follow it with `-f`.
- See where a unit's file lives and what's in it with `systemctl cat cron`.
- Write the mini mission's unit, start it, then `kill -9` its main PID and watch systemd restart it.
- Run `systemctl list-timers` and find the next scheduled job.

## Quiz

1. You installed nginx and ran sudo systemctl start nginx. After a reboot it isn't running. Why?
   - nginx crashed during the reboot
   - **start runs it now; only enable makes it start at boot** (answer)
   - Reboots always stop services
   Why: start and enable are separate. systemctl enable --now nginx does both: starts it now and at every boot.

2. A service shows "Active, failed". Where do you look first?
   - **journalctl -u myapp -n 50 (or systemctl status myapp, which shows the last lines)** (answer)
   - /etc/passwd
   - Reinstall the package
   Why: Everything the service printed, and systemd's own messages about why it stopped, are in the journal under its unit name.

3. You edited myapp.service and restarted it, but the change didn't apply. What did you forget?
   - **sudo systemctl daemon-reload** (answer)
   - Rebooting
   - chmod +x on the unit file
   Why: systemd reads unit files into memory. daemon-reload makes it read them again; until then the old version is used.

4. You need a different memory limit for the packaged postgresql.service. How?
   - Edit /usr/lib/systemd/system/postgresql.service directly
   - **sudo systemctl edit postgresql, which creates an override that survives package upgrades** (answer)
   - Copy the binary somewhere else
   Why: Files in /usr/lib/systemd/system belong to the package and are replaced on upgrade. systemctl edit writes a drop-in in /etc/systemd/system/postgresql.service.d/, which wins and stays.

5. What does Restart=on-failure do?
   - Restarts the service on every boot
   - **Restarts the service when it exits with an error or is killed, but not when you stop it** (answer)
   - Restarts the server
   Why: A crash, a non-zero exit code or a kill signal triggers a restart. systemctl stop does not. RestartSec sets the pause before each restart.

## Resources

- [systemctl(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/systemctl.1.html) (Ubuntu manpages)
- [systemd.service(5): every [Service] option](https://manpages.ubuntu.com/manpages/noble/man5/systemd.service.5.html) (Ubuntu manpages)
- [journalctl(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/journalctl.1.html) (Ubuntu manpages)
- [systemd.timer(5): timers instead of cron](https://manpages.ubuntu.com/manpages/noble/man5/systemd.timer.5.html) (Ubuntu manpages)
- [LPIC-1 objectives 101.3 and 108.2](https://wiki.lpi.org/wiki/LPIC-1_Objectives_V5.0) (Linux Professional Institute)
