1001Ferramentas
🔧 Dev

systemd Service (Advanced)

Create an advanced systemd unit file with Restart, RestartSec, MemoryLimit, CPUQuota, ProtectSystem, ProtectHome and User for hardening.

A systemd unit with limits and a restart policy

A systemd service unit fits in five lines, but the ones deciding production behaviour are almost never among those five. The restart policy, the interval between attempts and the memory and CPU limits are what separate a service that recovers on its own from one that restarts in a loop until it takes the machine down.

Fill in the description, the user, the command and the working directory, choose the restart policy and the limits, and the page assembles the complete unit with its three sections. The policy usually wanted is restarting on any exit rather than only on failure — that way the service comes back even after exiting with code zero by mistake.

The memory limit deserves an explanation: it is enforced by the kernel resource controller, and exceeding it gets the process killed by the out-of-memory mechanism. It is protection against leaks, not a performance setting. The CPU limit, by contrast, is proportional and merely slows the process under contention, without killing it. After writing the unit, systemd's configuration must be reloaded for it to see the changes.

Frequently asked questions

Which restart policy should I use?
Restart always is the sensible default for a service meant to stay up permanently. Restart on failure makes sense when exiting successfully is a legitimate state, as with a task that runs and finishes. Either way, pair it with an interval between attempts, or the service spins in a fast loop.
Why does my service stop trying to restart?
Because systemd has a limit on starts within a time window: exceed it and it gives up, marking the unit as failed. That is protection against infinite loops. Adjusting the interval between attempts usually solves it better than raising the limit, because it addresses the cause rather than the symptom.
Do I need to reload systemd after editing?
You do: it caches units and does not reread the file on its own. The daemon reload command is mandatory after creating or changing a unit, followed by restarting the service itself. Forgetting it is the most common cause of a change that appears to have no effect.

Related Tools