Systemd by Example: What Actually Happens When You Type systemctl restart nginx

Understanding the Sequence

Systemd is the heartbeat of most modern Linux systems.
When you run:

sudo systemctl restart nginx

you trigger a full chain of actions – not a single binary reload.
Systemd reads unit definitions, resolves dependencies, checks targets, and updates logs.
Knowing what happens gives you clarity when a service misbehaves.

You don’t need to fight systemd. You just need to understand its rhythm.

Step 1: Unit Discovery

Every service in systemd is a unit.
Units are configuration files stored under /lib/systemd/system or /etc/systemd/system.
When you type the restart command, systemd first finds the matching unit file:

systemctl cat nginx.service

This shows the full definition: ExecStart, ExecReload, dependencies, environment.

The unit file is the truth – not the documentation.

Step 2: Dependency Resolution

Systemd checks what nginx.service depends on.
Run:

systemctl list-dependencies nginx

You’ll see other units like network.target or syslog.target.
Before restarting, systemd ensures these are active or starts them in the correct order.
That’s why systemd feels reliable – it builds a temporary dependency graph before acting.

Step 3: The Stop Phase

Systemd sends a SIGTERM signal to the main Nginx process defined in the unit.
If it doesn’t exit in the allowed timeout (usually 90 seconds), systemd escalates with SIGKILL.
You can adjust this safely in your custom override:

sudo systemctl edit nginx

Then add:

[Service]
TimeoutStopSec=15s

Shorter timeouts improve recovery speed, but always test before deploying.

Step 4: The Start Phase

After the old process stops cleanly, systemd launches Nginx again using the ExecStart line.
The PID is tracked, logs go to journald, and the service status is refreshed.

Check it directly:

systemctl status nginx

You see the process tree, exit codes, and journal output – all in one view.

Step 5: Logging and Verification

Systemd records everything under the journal.
To see what actually happened during the restart:

journalctl -u nginx --since "5 minutes ago"

If something fails, this is your first stop.
It replaces long tail commands and greps across log files – structured and timestamped.

Step 6: Overrides and Control

Never edit system files directly.
Use:

systemctl edit nginx

It creates an override in /etc/systemd/system/nginx.service.d/.
This keeps changes persistent across package upgrades.
Control belongs to the operator, not the package maintainer.

Field Note

Systemd is not an enemy. It’s an evolution of process management.
When you know how its pieces connect – unit, dependency, journal – it becomes predictable.
Predictability is control, and control is stability.


Tom

Leave a comment