Run a service with systemd
systemd is the service manager on most Linux servers, and a unit file tells it how to start, stop and restart your program.
- Updated Nov 27, 2026
- Markdown
Write a systemd unit file and run a program as a service that starts at boot.
- A Linux server with sudo access
- A program to run, such as a small web server
You start your app in a terminal and it works. Then you close the laptop, the SSH session drops, and the app dies. Or the server reboots after an update and nothing comes back. A service manager solves this: it starts your program at boot, restarts it when it crashes and keeps its logs. On most Linux servers that manager is systemd.
How it works#
systemd is the first process the kernel starts, and it starts everything else. What it starts is described in unit files. A service unit says what command to run, as which user, in which folder, when to start it and what to do if it exits.
A unit file has sections. [Unit] describes the service and its ordering, such as After=network.target to start after the network is up. [Service] says how to run it: ExecStart is the command, User the account, WorkingDirectory the start folder and Restart the crash policy. [Install] says what enabling means. WantedBy=multi-user.target means start it in normal multi-user boot.
Two ideas are easy to mix up. Starting a service runs it now. Enabling it creates a link so it starts at boot. They are independent, which is why enable --now exists to do both.
systemd does not use a shell to run ExecStart. There is no PATH from your profile, no ~, and no pipes or && unless you call a shell yourself. Output goes to the journal, which you read with journalctl.
A worked example: at boot, systemd reads demo.service, sees WantedBy=multi-user.target and starts it after the network target. It runs ExecStart as user deploy in the working folder. The program prints to standard output, and systemd stores that in the journal. If the program crashes, Restart=on-failure starts it again after RestartSec. If you run systemctl stop demo, systemd sends it a stop signal and it stays down until you start it again.
Step 1: Write the unit file#
This example runs a small web server that serves a folder. Replace the user and paths with your own.
sudo nano /etc/systemd/system/demo.servicePaste this:
[Unit]
Description=Demo web server
After=network.target
[Service]
User=deploy
WorkingDirectory=/home/deploy/site
ExecStart=/usr/bin/python3 -m http.server 8000 --bind 127.0.0.1
Restart=on-failure
RestartSec=3
[Install]
WantedBy=multi-user.targetRun the service as a normal user such as deploy (see create a sudo user), not as root, unless the program really needs root. The --bind 127.0.0.1 part keeps the demo reachable only from the server itself. Restart=on-failure restarts it after a crash but not after a clean stop. RestartSec=3 waits three seconds first, so a broken program does not restart in a tight loop.
What you should see: no output. Check the file saved with cat.
Step 2: Load, enable and start it#
sudo systemctl daemon-reload
sudo systemctl enable --now demo.servicedaemon-reload makes systemd read the new file. enable makes it start at boot. --now also starts it right away.
What you should see: a line like Created symlink pointing at the multi-user target. No error means the unit was accepted.
Step 3: Look at the status#
systemctl status demo.serviceWhat you should see: active (running) in green, a Main PID, and the last few log lines. Press q to leave the status view.
Step 4: Manage it#
sudo systemctl restart demo.service
sudo systemctl stop demo.service
sudo journalctl -u demo.service -n 30After you edit the unit file, run sudo systemctl daemon-reload and then restart the service. To change a packaged unit without editing it, use sudo systemctl edit name, which creates an override file.
What you should see: restart and stop print nothing. The journal command shows the service’s own log lines, including start and stop messages.
Check it worked#
curl http://localhost:8000
systemctl is-enabled demo.service
systemctl is-active demo.serviceWhat you should see: an HTML directory listing from curl, then enabled and active. For the real test, run sudo reboot, log in again and check systemctl is-active demo.service. It should print active without you starting anything. To test the restart policy, find the process ID with systemctl show -p MainPID demo.service, run sudo kill <pid> and see it come back after a few seconds.
Edge cases and gotchas#
- systemd does not run your shell profile. Commands like
nodeorpython3may not be found without a full path. Find them withwhich, and write/usr/bin/python3or the real path inExecStart. - Environment variables must be set in the unit. Use
Environment=KEY=valueorEnvironmentFile=/etc/demo.envfor secrets, and give the env file mode 600. Quotes and$are handled differently than in a shell. After=network.targetdoes not mean the network is usable. For a service that needs an address or DNS at start, useAfter=network-online.targetandWants=network-online.target.- A crash loop is limited. If a service fails too many times in a short time, systemd stops retrying and marks it failed. Fix the cause, then run
sudo systemctl reset-failed demo.service. - Binding to a low port as a normal user fails. Ports below 1024 are privileged. Use a higher port behind a reverse proxy, or give a capability with
AmbientCapabilities=CAP_NET_BIND_SERVICE. - A unit file with wrong permissions can be ignored or warn. Keep unit files owned by root and not writable by others, such as mode 644.
- Enabled and active are different states.
is-enabledsays whether it starts at boot, andis-activesays whether it runs now. Check both. Restart=alwayshides crashes. The service keeps coming back and you may not notice. Watch the restart count insystemctl status.- Docker containers use a restart policy instead. If your app runs in Docker, see Docker restart policies rather than a unit file.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
Failed to enable unit: Unit file demo.service does not exist. | Wrong file name or folder | The file must end in .service and live in /etc/systemd/system |
status=203/EXEC | The path in ExecStart is wrong or not executable | Check with ls -l and use an absolute path |
status=217/USER | The user in User= does not exist | Create the user or fix the name |
status=200/CHDIR | WorkingDirectory does not exist | Create the folder or fix the path |
Warning: The unit file, source configuration file or drop-ins of demo.service changed on disk | You edited the unit without reloading | Run sudo systemctl daemon-reload |
Service flips between activating and failed | The program exits right away | Read journalctl -u demo.service for the real error |
bind: address already in use in the log | Another process holds the port | Find it with ss -ltnp and stop it or change the port |
Job for demo.service failed because the control process exited with error code. | The start command failed | Run systemctl status demo.service and journalctl -xeu demo.service |
Failed to start demo.service: Unit demo.service not found. | The file is missing or misnamed | Check the name and run daemon-reload |
Real-world scenario#
Omar runs an app by hand in a terminal with node server.js &. It works until he logs out, and then it dies. He writes a unit file with ExecStart=/usr/bin/node /home/deploy/app/server.js, sets User=deploy, adds Restart=on-failure, runs daemon-reload and enable --now.
The first start fails with status=203/EXEC: node is in a different path. which node shows /usr/local/bin/node, so he fixes the line, reloads and restarts. It now survives logout. After a sudo reboot the app is up again with no action from him.
He also reads journalctl -u app -f during a deploy, which is where he spots a missing environment variable.
Quick reference#
| Task | Command |
|---|---|
| Reload unit files | sudo systemctl daemon-reload |
| Start and enable | sudo systemctl enable --now name |
| Stop | sudo systemctl stop name |
| Restart | sudo systemctl restart name |
| Status | systemctl status name |
| Logs | sudo journalctl -u name -f |
| Clear failed state | sudo systemctl reset-failed name |
| Override a packaged unit | sudo systemctl edit name |
Security and safety notes#
- Do not run a public facing service as root. A bug in the program then gives an attacker root.
- Keep secrets in an env file with mode 600 rather than in the unit text, which many users can read.
Related lessons#
- Read logs with journalctl: where the output goes
- Docker restart policies: the container equivalent
- Linux file permissions explained: users and file access for services
- Zero downtime deploys: restarting without dropping users
Next#
Check what you learned
Frequently asked questions
Where do I put my own unit files?
Put them in /etc/systemd/system. Files in /lib/systemd/system belong to installed packages and can be replaced on update.
Why do I need daemon-reload?
systemd reads unit files into memory. After you create or edit one, daemon-reload makes it read the files again.
Why does my service work in my shell but fail under systemd?
systemd starts it with a clean environment: no PATH from your profile, no variables from your shell and a different working directory. Use full paths and set Environment or EnvironmentFile in the unit.
Should I use systemd or Docker to run my app?
Either works. systemd runs a program directly on the host. Docker runs it in a container with its own packages. Pick one way per app so two supervisors do not fight over it.
Sources
Keep going: guides and tutorials
- Install a Self-Hosted PaaS on Your Own Server in Five Minutes One installer download, one setup token, one sample app. The full Levelrail install on a fresh Linux server, with the checks and the fixes.
- Manage Secrets Self-Hosted: Env Vars and Master Key Rotation Set env vars and encrypted secrets on a self-hosted server, apply changes safely, and rotate the master key with no downtime without locking yourself out.