Writing Your First Real systemd Service Unit for a Long-Running App

Running an app under nohup or inside a screen session is how you lose it on the next reboot. A long-running process that matters to the business belongs to the init system, not to whoever last had a terminal open.

The gap between “it runs on the box” and “it is a managed service” is a single file. Get that file right and the process starts on boot, restarts when it crashes, runs as its own unprivileged user, and writes logs somewhere you can actually read them. Get it wrong, or skip it, and you are one reboot or one segfault away from an outage nobody notices until a customer does. This walks through a real unit file on Ubuntu 24.04 (systemd 255), directive by directive, and finishes with the three commands you will actually type.

Create the account before you create the unit

The first mistake is running the service as root or as your own login user. Neither should ever own a long-running process. Create a dedicated system account with no login shell and no home directory. It exists to own the process and nothing else.

Free · 4 minutes

Is your engineering team shipping safely, or quietly accumulating risk?

Fourteen questions on how work gets from idea to production — cadence, testing, rollback, and the key-person risk in your delivery. Banded finding on screen, full sheet by email.

# Dedicated, locked-down system account for the service
sudo useradd --system --no-create-home --shell /usr/sbin/nologin appsvc

# Somewhere for the code and config to live
sudo mkdir -p /opt/myapp
sudo chown -R appsvc:appsvc /opt/myapp

--system allocates a UID below 1000, which keeps it out of the normal user range; --shell /usr/sbin/nologin means that even if someone compromises the account, they cannot open an interactive shell with it. That is the whole point.

The unit file, in full

Put this at /etc/systemd/system/myapp.service. Everything under /etc/systemd/system is yours; the packages live under /lib/systemd/system and you never edit those directly. This example runs a Python process, but the shape is identical for a Go binary, a Node app or a Java jar.

[Unit]
Description=MyApp long-running worker
# Wait for the network stack, not just for interfaces to appear
After=network-online.target
Wants=network-online.target

[Service]
Type=exec
User=appsvc
Group=appsvc
WorkingDirectory=/opt/myapp

# The command that actually runs. Absolute paths only.
ExecStart=/opt/myapp/venv/bin/python -m myapp

# Restart policy: bring it back on any non-clean exit, but back off
Restart=on-failure
RestartSec=5

# Environment: inline for the harmless, a file for the secrets
Environment=PYTHONUNBUFFERED=1
EnvironmentFile=/etc/myapp/env

# Managed, writable state at /var/lib/myapp, owned by appsvc
StateDirectory=myapp

# --- Sandboxing: these cost nothing and buy a great deal ---
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
ProtectKernelTunables=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes

[Install]
WantedBy=multi-user.target

Why each line is there

Type=exec tells systemd the service is considered started once the binary has actually been executed. It is stricter than the old default Type=simple, which reports success the moment the process is forked, before execve has even run. If your app talks a readiness protocol you would use Type=notify and call sd_notify(3) from the code, but exec is the right default for most long-running processes.

Restart=on-failure and RestartSec=5 are the reason you are doing this at all. on-failure restarts on a non-zero exit, a signal or a timeout, but leaves the service stopped when it exits cleanly — which is what you want, because a clean stop is usually you stopping it. The default restart delay is 100ms; setting RestartSec=5 stops a genuinely broken process from spinning in a tight crash loop. Note the safety net systemd puts underneath this: by default it will give up if a unit restarts more than five times in ten seconds and mark it failed. That is a feature, not a bug — a service that cannot stay up needs a human, not another restart.

StateDirectory=myapp creates /var/lib/myapp, owned by the service user, before ExecStart runs. Use it instead of hand-creating and chown-ing directories in a shell script. It also plays correctly with ProtectSystem=strict, which is the point of the next section.

The sandboxing block is the part most first attempts skip, and it is close to free. ProtectSystem=strict mounts the entire filesystem read-only for the service, apart from the state and runtime directories systemd manages for it. ProtectHome=yes makes /home, /root and /run/user invisible. PrivateTmp=yes gives the service its own /tmp, so a shared-tmp symlink attack is not on the table. NoNewPrivileges=yes prevents the process (or anything it spawns) ever gaining privileges through a setuid binary. None of these change what your app does; all of them shrink what a compromise of it can reach.

If your app needs no persistent state and no static account at all, DynamicUser=yes is worth knowing about: systemd allocates a throwaway user for the lifetime of the process and turns on a batch of these protections implicitly (private tmp, IPC cleanup and tightened filesystem access among them). It is elegant, but a static account you can grant specific access to is easier to reason about for a first service. Start static; reach for DynamicUser once you understand what it implies.

Enable, start, and read it correctly

After writing or editing any unit, reload the manager so it re-reads the file on disk. Then enable and start in one step.

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

# Is it up, and did it come up cleanly?
systemctl status myapp.service

# Follow the logs live; -u scopes them to this unit only
journalctl -u myapp.service -f

# What happened in the last ten minutes?
journalctl -u myapp.service --since "10 min ago"

enable --now both starts the service and links it into multi-user.target so it comes back on reboot — the single behaviour nohup could never give you. Anything your app writes to stdout or stderr goes straight into the journal, tagged by unit, so journalctl -u is the only log command you need. No log file to rotate, no path to remember.

One last habit worth forming: run systemd-analyze security myapp.service. It scores the unit’s exposure and lists, in order, the hardening directives you have not yet set. It is the cheapest security review you will ever get, and it turns “is this locked down enough?” into a checklist. The same instrumentation is what lets you reason about a service being killed for the wrong reasons — which is a separate failure mode worth understanding, especially once memory pressure and swap enter the picture.

This is the unit for a process that runs continuously. If instead you want something that fires on a schedule — a nightly job, a periodic sync — the shape is different, and the service-plus-timer pattern is the one to reach for. Either way, the rule is the same: if it matters, it is a unit file, and it is owned by the init system — not by a terminal somebody forgot to close.

Free interactive tool

Website compliance checklist

What your site has to do, based on what it actually does

Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.

Most technology problems are not technology problems. They are control problems.

The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.