Skip to contentcloudvix
cloudvix
GuideServers & hosting

Run your app as a systemd service on Ubuntu 24.04

Denys DunaievskyiFounder, Cloudvix
  • 19 min read
  • Published
  • LevelIntermediate
Guides
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 hello needs no right to read it.
  • Changes to the unit file itself need sudo systemctl daemon-reload before 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.

On the serverbash
sudo mkdir -p /opt/hello
sudo adduser --system --group --no-create-home --home /opt/hello hello
getent passwd hello

Write 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.

On the server · /opt/hello/app.pybash
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 python3

Put 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.

On the server · /etc/hello.envenv
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.env

Write 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.

On the server · /etc/systemd/system/hello.servicebash
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
EOF
Warning

If 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.

On the serverbash
sudo systemd-analyze verify /etc/systemd/system/hello.service

Start 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.

On the serverbash
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:8090

Read 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.

On the serverbash
sudo journalctl -u hello --no-pager -n 20
sudo journalctl -u hello --since "10 minutes ago" --no-pager

Prove 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.

On the serverbash
sudo systemctl kill --signal=SIGKILL hello
sleep 5
systemctl is-active hello
systemctl show hello --property=NRestarts

Change 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.

On the serverbash
sudo sed -i 's/^GREETING=.*/GREETING=again/' /etc/hello.env
sudo systemctl restart hello
curl -s http://127.0.0.1:8090

See 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.

On the serverbash
systemd-analyze security hello --no-pager

Clean 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.

On the serverbash
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 hello

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.

About the author

Denys Dunaievskyi

Founder, Cloudvix

Runs Cloudvix and is responsible for the guides published here.

Related guides

Your server is a few clicks away.

Choose the plan and the system in one order form; the location too, when there is more than one.

Create server