How to Create a systemd Service in Linux: Unit File Tutorial
Explore create a systemd service in linux with syntax, flags, practical examples, real-world Linux administration workflows, and troubleshooting steps.
10 min read
Explore create a systemd service in linux with syntax, flags, practical examples, real-world Linux administration workflows, and troubleshooting steps.
- What systemd Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Interactive Builder for this Guide
Build your custom systemd syntax (How to Create a systemd Service in Linux: Unit File Tutorial)
[Unit] Description=Core API Node Service After=network-online.target Wants=network-online.target [Service] Type=simple User=www-data WorkingDirectory=/opt/myapp EnvironmentFile=/opt/myapp/.env ExecStart=/usr/bin/node dist/server.js Restart=on-failure RestartSec=5 NoNewPrivileges=true [Install] WantedBy=multi-user.target
After=network-online.targetWaits until host networking is online before launchingUser=www-dataRuns process with least privilege instead of rootRestart=on-failureAutomatically recovers process after crashes (delay 5s)NoNewPrivileges=trueSecurity hardening preventing child privilege escalationLearning how to create a systemd service in linux is one of the foundational capabilities required for modern Linux system administration, DevOps engineering, and production application deployment. Whether you are running a Node.js web application, a Python FastAPI microservice, a Go daemon, or a custom backup script, wrapping your binary in a systemd service unit transforms it from an ad-hoc terminal process into a resilient, managed operating system daemon.
To create a systemd service in Linux, define an ini-style unit file inside /etc/systemd/system/ with a .service extension containing [Unit], [Service], and [Install] configuration sections. After writing the file, notify PID 1 of changes with sudo systemctl daemon-reload, and then start and enable the daemon on system boot using sudo systemctl enable --now NAME.service.
As the universal init system and service manager adopted across Ubuntu, Debian, Red Hat Enterprise Linux (RHEL), Rocky Linux, AlmaLinux, Fedora, and Arch Linux, systemd supervises the entire lifecycle of processes. When managed by systemd, your application automatically restarts upon unexpected crashes, boots up in the correct dependency sequence after network interfaces initialize, logs directly to the unified journal, and runs inside sandboxed Linux control groups (cgroups).
By structuring your service files correctly with appropriate startup directives, restart policies, dedicated unprivileged system users, and filesystem isolation options, you ensure high availability and robust security posture for your production software stack.
What systemd Does and When to Use It
Architecturally, systemd evaluates unit files based on a strict priority hierarchy across three primary filesystem paths: /etc/systemd/system/ (highest priority, reserved for local administrator custom units and configuration overrides), /run/systemd/system/ (runtime-generated volatile units), and /usr/lib/systemd/system/ (package-managed default vendor units). When you create a file in /etc/systemd/system/, it overrides any identically named vendor unit provided by upstream distribution packages.
When systemd launches a service, PID 1 creates an isolated control group (cgroups v2) slice and scope for the unit (e.g. system.slice/myservice.service). This architectural isolation guarantees that any child processes, worker threads, or helper utilities spawned by the main process remain tracked inside that cgroup. When the service is stopped or restarted, systemd traverses the cgroup to cleanly terminate every descendant process, completely eliminating orphaned daemon leaks that historically plagued legacy SysVinit shell scripts.
Under the hood, systemd gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as Description=, After=, Type=, ExecStart= turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The systemd utility is packaged in systemd across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether systemd is installed and inspect which binary path and version your shell resolves:
type -a systemd
systemd --version 2>/dev/null || man -f systemd
# Illustrative output (reviewed against documentation)
systemd is /usr/bin/systemd
systemd (systemd)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y systemd
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y systemd
# Arch Linux
sudo pacman -S --noconfirm systemd
# Alpine Linux
sudo apk add --no-cache openrc
Command Syntax, Arguments, and Exit Status Codes
sudo nano /etc/systemd/system/NAME.service && sudo systemctl daemon-reload && sudo systemctl enable --now NAME.service
A standard systemd service unit file consists of plain text structured into three mandatory declarative sections: [Unit], [Service], and [Install]. The [Unit] block defines service metadata, human-readable descriptions, and dependency ordering using directives like Description=, After=network.target, and Wants=.
The [Service] block specifies runtime execution rules, including the absolute path to the executable (ExecStart=), the process startup type (Type=simple|exec|forking|notify|oneshot), process restart conditions (Restart=on-failure), unprivileged user/group ownership (User=, Group=), working directory paths, and environment variable files. Finally, the [Install] block specifies activation hooks, typically WantedBy=multi-user.target, which instructs systemd to link the service into the standard multi-user startup runlevel.
0— The systemctl command managing the service executed successfully.1— Generic systemctl management failure or unit configuration syntax error.2— Unit not found or service name does not exist in active search paths.3— Service unit is stopped, inactive, or entered a failed state.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
Description= | [Unit] Directive | A human-readable title describing the purpose and role of the service. |
After= | [Unit] Directive | Configures ordering; ensures this service starts only after specified units (e.g. network.target). |
Type= | [Service] Directive | Configures process startup behavior (simple, exec, forking, oneshot, dbus, notify). |
ExecStart= | [Service] Directive | The absolute path to the binary or script to execute, followed by arguments. |
Restart= | [Service] Directive | Configures restart policy (no, always, on-success, on-failure, on-abnormal). |
RestartSec= | [Service] Directive | The delay in seconds to wait before attempting to restart a failed service (e.g. 5s). |
User= / Group= | [Service] Directive | Specifies the non-root system user and group credentials under which the daemon executes. |
WorkingDirectory= | [Service] Directive | Sets the working directory from which relative file paths are resolved. |
WantedBy= | [Install] Directive | Defines the target runlevel (e.g. multi-user.target) where the service symlink is created. |
Choosing the right Type= directive in the [Service] section is the most critical architectural decision when writing a service file. Type=simple (the default) assumes the binary executed in ExecStart is the main daemon process that remains running in the foreground; systemd considers the service started immediately upon fork. For modern daemons, Type=exec is preferred over simple because systemd waits until the process binary is actually loaded into memory before continuing startup dependencies.
For legacy programs that fork themselves into the background and exit the parent shell, Type=forking is required, along with PIDFile=/run/app.pid so systemd can track the child PID. For scripts that run once and terminate (such as database migrations or backups), use Type=oneshot with RemainAfterExit=yes.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Basic systemd Service Unit for a Node.js or Python Application
Create a standard, production-ready service file in /etc/systemd/system/myapp.service that executes a web application under an unprivileged user.
sudo tee /etc/systemd/system/myapp.service << 'EOF'
[Unit]
Description=Production Node.js Web API Service
After=network.target
[Service]
Type=exec
User=www-data
Group=www-data
WorkingDirectory=/var/www/myapp
ExecStart=/usr/bin/node /var/www/myapp/server.js
Restart=on-failure
RestartSec=5s
Environment=NODE_ENV=production PORT=3000
[Install]
WantedBy=multi-user.target
EOF
# Illustrative output (reviewed against documentation)
Created /etc/systemd/system/myapp.service.
This unit specifies Type=exec, drops privileges to www-data, sets working directories, and automatically restarts the node app if it crashes with a non-zero exit code.
2. Reload systemd Configuration After Modifying Unit Files
Whenever you create or modify any unit file in /etc/systemd/system/, notify systemd PID 1 to rescan and re-serialize configuration.
sudo systemctl daemon-reload
# Illustrative output (reviewed against documentation)
# systemd re-parses all unit files in memory with zero output on success
daemon-reload rebuilds the dependency tree and loads new or modified service units into memory without restarting unrelated services.
3. Enable and Start the Service Immediately
Use systemctl enable --now to create the boot activation symlink and start the daemon immediately in a single command.
sudo systemctl enable --now myapp.service
# Illustrative output (reviewed against documentation)
Created symlink /etc/systemd/system/multi-user.target.wants/myapp.service → /etc/systemd/system/myapp.service.
The enable flag creates the symlink under multi-user.target.wants, while --now triggers an immediate start transition.
4. Inspect Service Status and Process Cgroup Hierarchy
Check whether the newly created service started cleanly, view its PID, and inspect recent log output.
systemctl status myapp.service
# Illustrative output (reviewed against documentation)
● myapp.service - Production Node.js Web API Service
Loaded: loaded (/etc/systemd/system/myapp.service; enabled; preset: enabled)
Active: active (running) since Thu 2026-10-22 19:40:12 UTC; 12s ago
Main PID: 18942 (node)
Tasks: 11 (limit: 4681)
Memory: 45.2M
CPU: 182ms
CGroup: /system.slice/myapp.service
└─18942 /usr/bin/node /var/www/myapp/server.js
Oct 22 19:40:12 server node[18942]: Server listening on port 3000 in production mode
status shows the unit is loaded, enabled, active, running under PID 18942, and shows the initial stdout log lines.
5. View Real-Time Service Logs with journalctl
Inspect combined stdout and stderr log streams generated by your custom service unit.
sudo journalctl -u myapp.service -f --output=cat
# Illustrative output (reviewed against documentation)
Server listening on port 3000 in production mode
[GET] /healthz - 200 OK (2ms)
[POST] /api/v1/auth/login - 200 OK (45ms)
journalctl -u filters the unified systemd journal exclusively for messages tagged with the unit name myapp.service.
6. Pass External Environment Files Securely
Reference an external environment file containing database passwords and secret keys instead of hardcoding them inside the service file.
sudo tee -a /etc/systemd/system/myapp.service << 'EOF'
# Add to [Service] section:
EnvironmentFile=/etc/myapp/production.env
EOF
sudo systemctl daemon-reload
sudo systemctl restart myapp.service
# Illustrative output (reviewed against documentation)
# EnvironmentFile directives allow setting strict chmod 600 permissions on sensitive credentials.
EnvironmentFile reads key-value pairs from an external file, enabling segregation of code configuration from secret credentials.
Real-World Workflows, Pipelines, and Shell Automation
Deploying a Hardened Python/FastAPI Production Microservice with systemd
End-to-end workflow creating an isolated service user, setting up a virtual environment, writing a hardened systemd unit with security sandboxing, and activating it.
#!/usr/bin/env bash
set -euo pipefail
# 1. Create dedicated system service account
sudo id -u apiuser &>/dev/null || sudo useradd -r -s /usr/sbin/nologin -d /opt/fastapi-app apiuser
# 2. Deploy hardened systemd unit file
sudo tee /etc/systemd/system/fastapi-app.service << 'EOF'
[Unit]
Description=FastAPI Production Microservice
After=network.target postgresql.service
Wants=postgresql.service
[Service]
Type=exec
User=apiuser
Group=apiuser
WorkingDirectory=/opt/fastapi-app
ExecStart=/opt/fastapi-app/venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000 --workers 4
Restart=always
RestartSec=3s
# Security and Sandboxing Directives
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/log/fastapi-app
CapabilityBoundingSet=
[Install]
WantedBy=multi-user.target
EOF
# 3. Reload daemon, enable and verify
sudo systemctl daemon-reload
sudo systemctl enable --now fastapi-app.service
sudo systemctl is-active --quiet fastapi-app.service && echo "FastAPI service is ACTIVE and RUNNING"
# Illustrative output (reviewed against documentation)
Created symlink /etc/systemd/system/multi-user.target.wants/fastapi-app.service → /etc/systemd/system/fastapi-app.service.
FastAPI service is ACTIVE and RUNNING
This production workflow incorporates modern security sandboxing (NoNewPrivileges, ProtectSystem=strict, PrivateTmp) to protect the host even if the web app is compromised.
Creating a Periodic One-Shot Maintenance Service with systemd Timer
Configure a oneshot service that executes a database backup script and pair it with a systemd timer as a modern, observable cron replacement.
#!/usr/bin/env bash
set -euo pipefail
# 1. Create the Oneshot Service Unit
sudo tee /etc/systemd/system/db-backup.service << 'EOF'
[Unit]
Description=Nightly PostgreSQL Database Backup
[Service]
Type=oneshot
User=postgres
ExecStart=/usr/local/bin/backup-database.sh
EOF
# 2. Create the Accompanying Timer Unit
sudo tee /etc/systemd/system/db-backup.timer << 'EOF'
[Unit]
Description=Run Database Backup Nightly at 02:00 UTC
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
EOF
# 3. Reload and activate timer
sudo systemctl daemon-reload
sudo systemctl enable --now db-backup.timer
sudo systemctl list-timers --all | grep db-backup
# Illustrative output (reviewed against documentation)
NEXT LEFT LAST PASSED UNIT ACTIVATES
Fri 2026-10-23 02:00:00 UTC 6h left n/a n/a db-backup.timer db-backup.service
systemd timers replace traditional cron jobs with persistent missed-event catching (Persistent=true) and clean journal logging for one-shot batch tasks.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding systemd inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
Configuring Restart=always without setting a reasonable RestartSec delay (e.g. 5s) or StartLimitIntervalSec can cause a crashing application to enter an infinite rapid restart loop. This can flood systemd-journald with millions of log messages, peg CPU utilization at 100%, and exhaust inode storage in /var/log.
Running custom services as the root superuser is a severe security vulnerability. Always create a dedicated system account with no login shell (e.g. useradd -r -s /usr/sbin/nologin appuser) and specify User=appuser and Group=appuser in the [Service] section. Restrict ownership of application source directories so the service user has read-only access to code files and write access only to designated temporary or log directories.
Take advantage of systemd's built-in Linux Security Module and namespace sandboxing features. Directives such as NoNewPrivileges=true prevent setuid privilege escalation, ProtectSystem=strict mounts /usr and /boot as read-only, ProtectHome=true conceals /home and /root, and PrivateTmp=true provisions an isolated private /tmp namespace that prevents temporary file tampering.
GNU/Linux, BSD, and BusyBox Implementation Differences
systemd unit files are portable across all Linux distributions utilizing systemd as PID 1 (Ubuntu 16.04+, Debian 8+, RHEL 7+, CentOS, Rocky Linux, Fedora, Arch Linux, openSUSE).
Non-systemd distributions—such as Alpine Linux (which utilizes OpenRC with shell scripts in /etc/init.d/), Void Linux (runit), or Devuan (SysVinit)—cannot parse systemd .service unit files. When building cross-distribution software, developers frequently ship both a .service unit file and an OpenRC init script.
Troubleshooting Common Errors and Diagnostics
Service fails to start with 'status=203/EXEC'
Root Cause: The binary path in ExecStart is incorrect, lacks executable permissions (+x), or points to a script with an invalid shebang line (e.g. missing /usr/bin/env bash).
Resolution: Verify that the path is absolute, check permissions with ls -l, and test the shebang line directly.
which node
ls -l /usr/bin/node
# In unit file, always use absolute path: ExecStart=/usr/bin/node /path/to/app.js
Changes to .service file are ignored after editing
Root Cause: systemd caches unit configurations in memory; modifications on disk are not evaluated until PID 1 is explicitly reloaded.
Resolution: Run sudo systemctl daemon-reload before issuing systemctl restart.
sudo systemctl daemon-reload
sudo systemctl restart myapp.service
Service enters 'failed' state with 'start-limit-hit'
Root Cause: The service crashed repeatedly more than 5 times within a 10-second window, triggering systemd's burst rate protection.
Resolution: Inspect the failure logs with journalctl -u myapp.service -e, fix the bug, and reset the failure counter.
sudo journalctl -u myapp.service -n 50 --no-pager
sudo systemctl reset-failed myapp.service
sudo systemctl start myapp.service
Alternatives, Related Commands, and Related Tutorials
- List Linux Services with systemctl: Status, Units, and States — Practical syntax, flags, and examples for
systemctl. - systemctl Command in Linux: Start, Stop, Enable, and Manage Services — Practical syntax, flags, and examples for
systemctl. - reboot Command in Linux: Restart with systemctl and shutdown — Practical syntax, flags, and examples for
reboot. - How to Kill a Process in Linux: kill, killall, and pkill Guide — Practical syntax, flags, and examples for
kill. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

UNIX and Linux System Administration Handbook, 5th Edition
Frequently Asked Questions
Quick answers to common questions and configurations
/etc/systemd/system/. Never edit vendor-supplied unit files in /usr/lib/systemd/system/ directly because package updates will overwrite your changes.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides



Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!