On this page
Key takeaways
- A service should not run as root or as your own login.
- Systemd reads the file as root and hands the values to the program, so
helloneeds no right to read it. - Changes to the unit file itself need
sudo systemctl daemon-reloadbefore the restart; changes to the settings file do not.
A systemd service is how Ubuntu starts a program at boot, starts it again when it crashes and collects its output in one log. This guide runs a small web app as a service on Ubuntu 24.04, under its own user without a login and with its settings in a separate file. You read its log, prove that it comes back after a crash, and fence it in with a few lines of the unit file.
Before you start
You need an Ubuntu 24.04 server and a user with sudo, as in the first-hour guide. The guide runs a ten-line Python program, so nothing has to be installed beyond python3, which Ubuntu normally has; the second step prints where it is. Replace the program with your own later: the unit file stays almost the same. The last step removes everything again.
- an Ubuntu 24.04 server and a user with sudo
python3(the second step shows where it is)- ten minutes; no restart of the server is needed
The steps
Create a user for the program
A service should not run as root or as your own login. adduser --system creates an account for a program: no password, no login shell and, with --no-create-home, no home folder. The folder /opt/hello is made by hand and stays owned by root, so the program cannot change its own code. --group gives the account a group of the same name. The last command shows the account; its shell must be /usr/sbin/nologin.
sudo mkdir -p /opt/hello
sudo adduser --system --group --no-create-home --home /opt/hello hello
getent passwd helloWrite the program
The program answers every request with one line that holds the value of the variable GREETING, and it listens on 127.0.0.1:8090 only, so it is not reachable from the internet. command -v python3 prints the full path of Python, which the unit file needs.
sudo tee /opt/hello/app.py > /dev/null <<'EOF'
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
class Hello(BaseHTTPRequestHandler):
def do_GET(self):
body = ("hello from " + os.environ.get("GREETING", "nobody") + "\n").encode()
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
HTTPServer(("127.0.0.1", 8090), Hello).serve_forever()
EOF
command -v python3Put the settings in a file, not in the unit
A file in /etc with one KEY=value per line keeps settings and secrets out of the program and out of the unit file. install -m 600 /dev/null FILE creates an empty file that only root can read, before any value is written to it. Systemd reads the file as root and hands the values to the program, so hello needs no right to read it. The last command must show -rw------- and root root.
sudo install -m 600 -o root -g root /dev/null /etc/hello.env
echo 'GREETING=world' | sudo tee /etc/hello.env > /dev/null
sudo ls -l /etc/hello.envWrite the unit file
The [Unit] part says when to start: After=network.target means: start after the basic network setup has run; it does not wait until the server has an address or can reach other hosts. A program that has to reach other hosts at start, such as a database or an API, adds Wants=network-online.target and After=network-online.target. [Service] says how. User= and Group= drop the rights, EnvironmentFile= loads the settings, ExecStart= is the command with its full path, and Restart=on-failure with RestartSec=3 starts the program again three seconds after a crash. The last four lines of that part fence the program in: it may not gain new privileges (NoNewPrivileges), it gets a private /tmp (PrivateTmp), it sees the file system as read-only (ProtectSystem=strict) and it cannot read home folders (ProtectHome). [Install] ties the service to the normal boot target, so that enable starts it at boot.
sudo tee /etc/systemd/system/hello.service > /dev/null <<'EOF'
[Unit]
Description=Hello demo app
After=network.target
[Service]
User=hello
Group=hello
WorkingDirectory=/opt/hello
EnvironmentFile=/etc/hello.env
ExecStart=/usr/bin/python3 /opt/hello/app.py
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
[Install]
WantedBy=multi-user.target
EOFIf your program has to write files, ProtectSystem=strict makes that fail with permission errors. Name the folder it may write to with ReadWritePaths=/var/lib/hello, and create that folder owned by the service user.
Check the file
systemd-analyze verify reads the unit file and complains about mistakes such as a misspelled key or a missing program. No output means that it found nothing to complain about. Fix what it names before you start the service.
sudo systemd-analyze verify /etc/systemd/system/hello.serviceStart it, and start it at boot
daemon-reload makes systemd read the new file. enable --now starts the service now and at every boot. The status must say active (running), is-enabled must say enabled, and the curl line must answer hello from world.
sudo systemctl daemon-reload
sudo systemctl enable --now hello
sudo systemctl status hello --no-pager
systemctl is-enabled hello
curl -s http://127.0.0.1:8090Read the log
Everything the program writes to its output or error stream lands in the journal; there is no log file to set up. -u hello limits the output to this service, and every request the program has served is a line. To watch the log live, add -f and stop it with Ctrl+C. You need sudo here unless your user is in the adm or systemd-journal group.
sudo journalctl -u hello --no-pager -n 20
sudo journalctl -u hello --since "10 minutes ago" --no-pagerProve that it comes back
The first command kills the program the hard way, as a crash would. With Restart=on-failure, systemd starts it again after three seconds. After the wait, the service must be active and NRestarts must read NRestarts=1.
sudo systemctl kill --signal=SIGKILL hello
sleep 5
systemctl is-active hello
systemctl show hello --property=NRestartsChange a setting
Edit the settings file and restart the service; the program reads its settings only when it starts. The answer of curl must now carry the new word. Changes to the unit file itself need sudo systemctl daemon-reload before the restart; changes to the settings file do not.
sudo sed -i 's/^GREETING=.*/GREETING=again/' /etc/hello.env
sudo systemctl restart hello
curl -s http://127.0.0.1:8090See how well the unit is fenced in
systemd-analyze security scores a unit from 0 (fenced in) to 10 (exposed) and lists the settings that would lower the score. Treat it as a reading aid, not as a goal: some settings it asks for would stop a normal program from working. The few lines in this unit already close the large holes.
systemd-analyze security hello --no-pagerClean up
This stops the service and its start at boot, deletes the files and removes the user. The last line removes the group only if it is still there.
sudo systemctl disable --now hello
sudo rm /etc/systemd/system/hello.service /etc/hello.env
sudo systemctl daemon-reload
sudo rm -r /opt/hello
sudo deluser hello
getent group hello && sudo delgroup helloLet an assistant do it, with a plan first
If you use an AI assistant that can run SSH commands, paste the prompt below. It works with SSH access as a user with sudo. If the assistant should also order the server, use a Cloudvix API key, which has limits (up to €500 a month and 25 servers), instead of your account login.
The prompt makes the assistant look first, show a plan before it acts, check each step and stop when a check fails. It names settings only, does not open files that hold secret values and creates the settings file empty; you type the values into it yourself with sudoedit. It must tell you before it stops a program that already runs in another way.
You are helping me run a program as a systemd service on an Ubuntu 24.04 server at SERVER_IP. Connect over SSH as the user ops, which has sudo.
Rules:
1. Before you change anything, show me a numbered plan and wait for my yes.
2. After every step, run a check command and show me its output.
3. If a check fails, stop and tell me. Do not try to work around it.
First only look: find out what the program is and how it is started today (ask me if you cannot tell), where its files are, which port it listens on and which settings it reads (names only: do not open files that hold secret values). Then propose a plan: a dedicated system user without a login (adduser --system --group), the settings file /etc/NAME.env, created empty with install -m 600 -o root -g root /dev/null /etc/NAME.env, which I fill in myself with sudoedit, a unit file /etc/systemd/system/NAME.service with User, Group, WorkingDirectory, EnvironmentFile, ExecStart with the full path, Restart=on-failure, NoNewPrivileges=true, PrivateTmp=true, ProtectSystem=strict and ProtectHome=true (add ReadWritePaths only for folders the program must write to), then systemd-analyze verify, daemon-reload, enable --now, and the status and the last 20 journal lines of the unit. Do not print the contents of the settings file or any secret in the chat. If the program already runs in another way, tell me before you stop it.
At the end, prove the restart with systemctl kill --signal=SIGKILL and show NRestarts, and list what you changed with the command that undoes each change.If something goes wrong
status=203/EXEC
systemd could not start the program. The path in ExecStart= is wrong, or the file cannot be executed. Use the full path (command -v python3 shows it) and check the spelling of the file name.
status=217/USER
The user named in User= does not exist. getent passwd hello must print a line; if it does not, create the account as in the first step.
Start request repeated too quickly
The program exits at once, and systemd gave up after too many attempts. Read the reason with sudo journalctl -u hello --no-pager -n 30, fix it, clear the failed state with sudo systemctl reset-failed hello and start the service again.
My change to the unit file has no effect
Systemd keeps a copy of the file in memory. After every edit of a unit file, run sudo systemctl daemon-reload and restart the service. When you forget, systemctl status warns that the unit file changed on disk.
Questions people ask
Systemd or Docker for my app?
Both work. A systemd service suits a single program that you install on the server, with a language runtime that is already there. Docker suits programs that bring many dependencies, need a specific version or should be kept apart from the rest. You can mix them: the Docker daemon itself is a systemd service.
What is the difference between Restart=on-failure and Restart=always?
on-failure restarts the program after a crash, a non-zero exit code or a timeout, but not after a clean exit with code 0, and not after you stop it with systemctl stop. always also restarts after a clean exit. Use always for programs that should never end and on-failure for the rest.
Where do I put passwords and keys?
In the settings file that only root can read, as in the third step; never in the unit file, which every user on the server can read. The guide on secrets and .env files shows how to keep them out of git as well.
Where to go next
To keep passwords and keys out of the unit file and out of git, read secrets and .env files. For the other checks on a server that goes live, use the security checklist, and if your program is a container instead, start with the Docker guide.
Runs Cloudvix and is responsible for the guides published here.