Chapter 1 · Lesson 10 of 19
Server basics

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.

By the end you will

Write a systemd unit file and run a program as a service that starts at boot.

Time
18 min
Level
Beginner
Check
4 questions
You need
  • 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.

bash
sudo nano /etc/systemd/system/demo.service

Paste this:

ini
[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.target

Run 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#

bash
sudo systemctl daemon-reload
sudo systemctl enable --now demo.service

daemon-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#

bash
systemctl status demo.service

What 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#

bash
sudo systemctl restart demo.service
sudo systemctl stop demo.service
sudo journalctl -u demo.service -n 30

After 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#

bash
curl http://localhost:8000
systemctl is-enabled demo.service
systemctl is-active demo.service

What 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 node or python3 may not be found without a full path. Find them with which, and write /usr/bin/python3 or the real path in ExecStart.
  • Environment variables must be set in the unit. Use Environment=KEY=value or EnvironmentFile=/etc/demo.env for secrets, and give the env file mode 600. Quotes and $ are handled differently than in a shell.
  • After=network.target does not mean the network is usable. For a service that needs an address or DNS at start, use After=network-online.target and Wants=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-enabled says whether it starts at boot, and is-active says whether it runs now. Check both.
  • Restart=always hides crashes. The service keeps coming back and you may not notice. Watch the restart count in systemctl status.
  • Docker containers use a restart policy instead. If your app runs in Docker, see Docker restart policies rather than a unit file.

Troubleshooting#

SymptomLikely causeFix
Failed to enable unit: Unit file demo.service does not exist.Wrong file name or folderThe file must end in .service and live in /etc/systemd/system
status=203/EXECThe path in ExecStart is wrong or not executableCheck with ls -l and use an absolute path
status=217/USERThe user in User= does not existCreate the user or fix the name
status=200/CHDIRWorkingDirectory does not existCreate the folder or fix the path
Warning: The unit file, source configuration file or drop-ins of demo.service changed on diskYou edited the unit without reloadingRun sudo systemctl daemon-reload
Service flips between activating and failedThe program exits right awayRead journalctl -u demo.service for the real error
bind: address already in use in the logAnother process holds the portFind 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 failedRun systemctl status demo.service and journalctl -xeu demo.service
Failed to start demo.service: Unit demo.service not found.The file is missing or misnamedCheck 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#

TaskCommand
Reload unit filessudo systemctl daemon-reload
Start and enablesudo systemctl enable --now name
Stopsudo systemctl stop name
Restartsudo systemctl restart name
Statussystemctl status name
Logssudo journalctl -u name -f
Clear failed statesudo systemctl reset-failed name
Override a packaged unitsudo 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.

Next#

What is SSH and how does it work.

Check what you learned4 questions
1Where should your own unit files go?
2What does systemctl enable --now do?
3You edited a unit file. What is the next step?
4ExecStart=python3 app.py fails with status 203/EXEC. What is the fix?

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

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios