If you have ever run an app on a Linux server, you're probably familiar with this situation: you start the app from the terminal, everything works, and the moment you close the SSH session the app dies with it. Or worse, the server reboots in the middle of the night and your app never comes back until someone complains.
Many people work around this with nohup, screen, or tmux. That works for a while, but the app still won't start on boot, won't be restarted when it crashes, and its logs end up scattered who knows where.
The thing is, almost every modern Linux distro already ships with the solution: systemd. With one short configuration file, your app can run in the background, start by itself on boot, and be restarted automatically when it dies unexpectedly.
In this article, we'll cover how to create a systemd service for your own app from start to finish: understanding the unit file, enabling autostart, reading logs with journalctl, testing automatic restarts, and adding basic hardening. Let's get started!
What is systemd?
systemd is the init system and service manager used by most Linux distros today, including Ubuntu, Debian, Fedora, and Arch Linux. It is the first process the kernel starts at boot (PID 1), and it is responsible for starting and supervising every other service on the system.
Everything systemd manages is called a unit, and every unit is defined by a text file called a unit file. There are several unit types, such as .service for services, .timer for scheduled jobs, and .socket for socket activation. In this article we focus on the most commonly used one: .service.
You have actually been talking to systemd all along. Every time you run sudo systemctl restart nginx or systemctl status ssh, you are talking to systemd. Now we are going to make your own app a first-class citizen, just like Nginx or SSH.
Why Use a systemd Service?
Here are the benefits of running your app as a systemd service:
- Starts on boot:
enableit once, and the app comes up every time the server starts. - Restarts on crash: systemd watches the app's process and brings it back according to the rules you define.
- Centralized logs: everything the app writes to stdout and stderr goes into the journal automatically and can be read with
journalctl. - Runs as a restricted user: the app doesn't need to run as root; a single
User=line takes care of it. - Nothing extra to install: systemd is already on your server.
- Built-in security features: systemd can restrict the app's access to the filesystem with just a few lines of configuration.
So what about process managers like PM2? For Node.js apps, PM2 offers conveniences such as cluster mode and zero-downtime reloads, as we covered in how to deploy Next.js to a VPS with PM2 and Nginx. systemd, however, is universal: it works for apps written in Python, Go, Rust, Java, Bash scripts, or anything else you can run from a terminal.
Understanding the Unit File Structure
Before we get hands-on, let's look at what a unit file is made of. It has three main sections:
| Section | Purpose | Common options |
|---|---|---|
[Unit] |
Description and relationships to other units | Description=, After=, Wants= |
[Service] |
How to run and supervise the app | ExecStart=, User=, Restart=, Environment= |
[Install] |
When the service is started at boot | WantedBy= |
Unit files can also live in several locations. You only need to remember two:
/etc/systemd/system/: units created by the administrator. This is where we will put our own service./usr/lib/systemd/system/: units shipped by distro packages. Don't edit files here directly, because they are overwritten when the package is updated.
If a file with the same name exists in both locations, the one in /etc/systemd/system/ wins.
Preparation
Before we begin, make sure you have:
- A server or computer running Ubuntu 24.04 LTS or 26.04 LTS. The commands in this article are written for these two versions. Ubuntu 24.04 ships systemd 255, and every option used here is available in that version. Other systemd-based distros (Debian, Fedora, Raspberry Pi OS) can generally follow the same steps.
sudoaccess. If your server is brand new, it's a good idea to go through how to secure a new Linux VPS first.- Python 3, which is installed by default on Ubuntu. We only use it for the example app.
You can check the installed systemd version with this command:
systemctl --versionAs an example, we will build a tiny web app called halo-app. Of course, you can swap it for your own app. The only things that change are the ExecStart= line and the folder location.
How to Create a systemd Service
Step #1: Prepare the Example App
First, create a folder for the app under /opt:
sudo mkdir -p /opt/halo-appThen create the app file:
sudo nano /opt/halo-app/app.pyPaste in the following code. It is just a simple HTTP server that answers every request with a message:
#!/usr/bin/env python3
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
PORT = int(os.environ.get("PORT", "8000"))
PESAN = os.environ.get("PESAN", "Halo dari systemd!")
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.end_headers()
self.wfile.write((PESAN + "\n").encode())
if __name__ == "__main__":
print(f"Server berjalan di port {PORT}", flush=True)
HTTPServer(("127.0.0.1", PORT), Handler).serve_forever()Save the file by pressing Ctrl+X, then Y, and Enter.
Notice that the app reads its PORT and PESAN (the message) settings from environment variables. We will set them through systemd later.
Before turning it into a service, make sure the app runs manually:
python3 /opt/halo-app/app.pyIf you see Server berjalan di port 8000 ("server running on port 8000"), the app is fine. Stop it with Ctrl+C.
Important: always test a command manually before putting it into a unit file. If the command fails in your terminal, systemd won't be able to run it either.
Step #2: Create a Dedicated User for the Service
By default, systemd services run as root. That is dangerous: if your app has a vulnerability, an attacker immediately gets full access to the server. So let's create a dedicated system user that cannot log in and has no home directory:
sudo useradd --system --no-create-home --shell /usr/sbin/nologin haloappWe leave the app files in /opt/halo-app owned by root. The haloapp user only needs to read them, not modify them. That way, even if the app gets compromised, the attacker cannot replace its code.
Step #3: Write the Unit File
Now for the main part. Create a new unit file with this command:
sudo nano /etc/systemd/system/halo-app.serviceAdd the following configuration:
[Unit]
Description=Halo App - contoh service systemd
After=network.target
[Service]
Type=exec
User=haloapp
WorkingDirectory=/opt/halo-app
ExecStart=/usr/bin/python3 /opt/halo-app/app.py
Environment=PORT=8000
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.targetHere is what each line does:
- Description: a short description shown in
systemctl statusand in the logs. - After=network.target: the service is started after basic networking is up. This option only controls ordering, not dependency.
- Type=exec: systemd considers the service started once the app's binary has actually been executed. The systemd documentation recommends this type for long-running services, because errors such as a missing program file or a wrong user are caught right at
start. With the default type (simple),systemctl startcan report success even when the program failed to launch. - User: the user that runs the app.
- WorkingDirectory: the app's working directory.
- ExecStart: the command that starts the app. Get in the habit of writing the full path to the program (
/usr/bin/python3, notpython3). You can find a program's path withwhich python3. - Environment: sets an environment variable for the app.
- Restart=on-failure: the app is restarted if it stops abnormally (non-zero exit code, killed by a signal, or a timeout). If you stop it with
systemctl stop, it is not restarted. - RestartSec=5: wait 5 seconds before restarting. The default is only 100 milliseconds, which is too fast for an app that crashes because, say, the database isn't ready yet.
- WantedBy=multi-user.target: when enabled, the service is started as part of a normal boot.
Note:
ExecStart=is not a shell. Pipes (|), redirects (>), and&&are not understood there. If you really need them, wrap the command in a shell, for exampleExecStart=/bin/sh -c 'command-a | command-b', or better yet, put it in its own script file.
Before moving on, check the unit file for mistakes with this command:
sudo systemd-analyze verify /etc/systemd/system/halo-app.serviceIf no message about halo-app.service shows up, the file is written correctly.
Step #4: Enable and Start the Service
Every time you create or change a unit file, systemd has to be told to re-read its configuration:
sudo systemctl daemon-reloadNext, enable autostart and start the service right away:
sudo systemctl enable --now halo-appThe output looks roughly like this:
Created symlink /etc/systemd/system/multi-user.target.wants/halo-app.service → /etc/systemd/system/halo-app.service.Keep in mind that enable and start are two different things. start runs the service now, while enable makes it start on boot. The --now option combines both in a single command.
Step #5: Check the Status and Logs
Check whether the service is running with this command:
systemctl status halo-appThe output looks roughly like this:
● halo-app.service - Halo App - contoh service systemd
Loaded: loaded (/etc/systemd/system/halo-app.service; enabled; preset: enabled)
Active: active (running) since Sun 2026-11-15 10:00:00 WIB; 8s ago
Main PID: 1234 (python3)
Tasks: 1 (limit: 2271)
Memory: 9.1M
CPU: 60ms
CGroup: /system.slice/halo-app.service
└─1234 /usr/bin/python3 /opt/halo-app/app.py
Nov 15 10:00:00 server systemd[1]: Started halo-app.service - Halo App - contoh service systemd.
Nov 15 10:00:00 server python3[1234]: Server berjalan di port 8000There are two things to look at. enabled on the Loaded line means autostart is on, and active (running) on the Active line means the app is running. Press q to leave the status view.
Now try calling the app:
curl http://127.0.0.1:8000If the output is Halo dari systemd!, congratulations, your first service is up and running!
To view the app's logs, use journalctl with the -u (unit) option:
journalctl -u halo-app -n 50The -n 50 option shows the last 50 lines. To follow the logs live (like tail -f), use -f:
journalctl -u halo-app -fYou don't have to set up any log files. Everything the app writes to stdout and stderr is captured by the journal automatically, complete with timestamps and the process name.
Tip for Python: if your
print()output doesn't show up injournalctlright away, Python's output buffering is the cause. Addflush=Trueas in the example above, or addEnvironment=PYTHONUNBUFFERED=1to the unit file.
Step #6: Test the Automatic Restart
Now the question is: does the app really get restarted when it crashes? Let's prove it by killing the process forcefully:
sudo systemctl kill -s SIGKILL halo-appCheck the status right away:
systemctl status halo-appOn the Active line you will see something like this:
Active: activating (auto-restart) (Result: signal) since Sun 2026-11-15 10:05:00 WIB; 2s agoWait 5 seconds (matching RestartSec=5), then check again. The status goes back to active (running) with a new Main PID. Pretty cool, right?
Here are the most commonly used Restart= values:
| Value | When the app is restarted | Good for |
|---|---|---|
no (default) |
Never | One-shot scripts |
on-failure |
When it stops abnormally | Most server apps (recommended) |
always |
Always, unless stopped via systemctl stop |
Apps that must never stay down |
Good to know: systemd has a rate limit so that a service that keeps failing isn't restarted forever. By default the limit is 5 starts within 10 seconds. Once it is exceeded, the service is marked as failed with
start-limit-hitand no further attempts are made. WithRestartSec=5, this limit can never be reached, so systemd keeps retrying every 5 seconds. To change the limit, useStartLimitIntervalSec=andStartLimitBurst=in the[Unit]section.
Step #7: Keep Configuration in an Environment File
Writing Environment= directly in the unit file is fine for one or two variables. For larger or secret configuration (database passwords, API keys), it's better to move it to a separate file.
Create the environment file with this command:
sudo nano /etc/halo-app.envAdd variables in NAME=value format, one per line:
PORT=8000
PESAN=Halo, ini pesan dari file environment!Since this file may hold secrets, restrict it so that only root can read it. systemd reads the file before launching the app, so the haloapp user doesn't need access to it:
sudo chmod 600 /etc/halo-app.envNext, open the unit file again:
sudo nano /etc/systemd/system/halo-app.serviceReplace the Environment=PORT=8000 line with this one:
EnvironmentFile=/etc/halo-app.envReload the systemd configuration, then restart the service to apply the change:
sudo systemctl daemon-reload
sudo systemctl restart halo-appTest again with curl:
curl http://127.0.0.1:8000If the output has changed to Halo, ini pesan dari file environment!, the environment file is being read.
Step #8: Add Basic Hardening
Nice, isn't it? But we're not done yet. systemd has sandboxing features that limit what the app is allowed to touch. This is really valuable: if your app ever gets compromised, the damage an attacker can do becomes much smaller.
Open the unit file again and add these lines to the [Service] section:
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=trueIn short:
- NoNewPrivileges=true: the app's process and all of its children can never gain additional privileges, for example through
sudoor setuid programs. - PrivateTmp=true: the app gets its own private
/tmp, separate from other apps. - ProtectSystem=strict: almost the entire filesystem becomes read-only for the app.
- ProtectHome=true:
/home,/root, and/run/userare not accessible at all.
Apply the changes with these commands:
sudo systemctl daemon-reload
sudo systemctl restart halo-appThen confirm the service still works with systemctl status halo-app and curl http://127.0.0.1:8000.
Careful: sandboxing options can stop an app from running if it genuinely needs the access you just closed. If your app lives inside
/home, don't useProtectHome=true. If the app needs to write files (an SQLite database, uploads), addStateDirectory=halo-app. systemd will create/var/lib/halo-app, writable by the service user. Alternatively, open a specific folder withReadWritePaths=/path/to/folder. Add the options one at a time and test after each.
systemd also ships a tool that rates how "exposed" a service is:
systemd-analyze security halo-appThis command prints a long list of hardening options along with an exposure score from 0 (safest) to 10 (most exposed). There's no need to chase a perfect score. Use the list as a reference for which options you could add next.
Commonly Used systemctl and journalctl Commands
Here is a summary of the commands for day-to-day service management:
| Command | Purpose |
|---|---|
sudo systemctl start halo-app |
Start the service |
sudo systemctl stop halo-app |
Stop the service |
sudo systemctl restart halo-app |
Stop and start it again |
sudo systemctl enable halo-app |
Enable autostart on boot |
sudo systemctl disable halo-app |
Disable autostart |
systemctl status halo-app |
Show status and the latest logs |
systemctl is-enabled halo-app |
Check whether autostart is on |
systemctl cat halo-app |
Print the unit file currently in use |
sudo systemctl daemon-reload |
Re-read unit files after a change |
journalctl -u halo-app -f |
Follow logs live |
journalctl -u halo-app --since "1 hour ago" |
Logs from the last hour |
journalctl -u halo-app -b |
Logs since the last boot |
Troubleshooting Common Problems
If the service fails to start, always begin with these two commands: systemctl status halo-app and journalctl -u halo-app -n 50. Here are the messages you'll run into most often:
| Symptom | Cause | Fix |
|---|---|---|
status=203/EXEC |
The program in ExecStart= cannot be executed |
Check the path, the execute permission (chmod +x), and the script's shebang line |
status=217/USER |
The user in User= doesn't exist |
Check the user name, or create the user (Step #2) |
status=200/CHDIR |
The WorkingDirectory= folder is missing or inaccessible |
Check the path and folder permissions, and the ProtectHome= option |
start-limit-hit |
The service failed repeatedly in a short time | Fix the cause, then run sudo systemctl reset-failed halo-app |
changed on disk warning |
The unit file was changed but not reloaded | Run sudo systemctl daemon-reload |
| Changes have no effect | The service hasn't been restarted | Run sudo systemctl restart halo-app |
One more thing that often causes confusion: if your app has to connect to the internet or another server right when it starts, After=network.target may not be enough. Use this pair in the [Unit] section so the service waits until the network is actually online:
After=network-online.target
Wants=network-online.targetWhat About Services Installed by Packages?
Everything above applies to services you create yourself. For services installed by a package (such as Nginx, Docker, or Ollama), don't modify the original unit file. Use this command instead:
sudo systemctl edit nginxIt creates a drop-in file at /etc/systemd/system/nginx.service.d/override.conf. Its contents are merged with the original unit file, so your settings survive package updates. You can see a real-world example in how to install Ollama on Ubuntu, where we set environment variables for the Ollama service.
Conclusion
From this article, we can conclude that creating a systemd service is not complicated at all. With a single unit file of a dozen or so lines in /etc/systemd/system/, your app runs in the background, starts automatically on boot, restarts when it crashes, and has its logs neatly recorded in the journal.
Things to Remember
- Keep your own unit files in
/etc/systemd/system/, and rundaemon-reloadevery time you change them. enableis for autostart on boot,startis for running now. Combine them withenable --now.- Use
Type=exec,Restart=on-failure, andRestartSec=for long-running apps. - Don't run your app as root. Create a dedicated user and add a sensible amount of sandboxing.
- When something goes wrong,
systemctl statusandjournalctl -uare your best friends.
Next Steps
Once you're comfortable with .service units, you can move on to systemd timers as a replacement for cron, or put a reverse proxy such as Nginx in front of your app so it can be reached through a domain with HTTPS.
Resources and Useful Links
- systemd.service documentation: every option in the
[Service]section. - systemd.unit documentation: options in the
[Unit]and[Install]sections, and unit file locations. - systemd.exec documentation: environment, user, and sandboxing options.
- journalctl documentation: every option for reading logs.
If you have questions or run into trouble while trying this out, feel free to ask. Stay tuned to Teknotut!
I hope this article helps.



