Unix - Systemd Unit File Structure
A systemd unit file defines how a service, device, mount point, socket, or other component should be started, stopped, and managed.
These files are typically located in:
/etc/systemd/system/ (administrator overrides and custom units)
/usr/lib/systemd/system/ (distribution-provided units)
/run/systemd/system/ (runtime units)
A unit file is a simple text file divided into standardized sections.
1. [Unit] Section
This section describes the unit at a high level and defines its relationships with other units.
Common directives:
[Unit]
Description=Short description of the service
Documentation=URL or man pages
After=network.target
Before=multi-user.target
Requires=network-online.target
Wants=mysqld.service
Meaning:
-
Description: human-readable name.
-
Documentation: where to find its docs.
-
After/Before: ordering — when to start relative to others.
-
Requires: hard dependency; failure stops this unit.
-
Wants: soft dependency; failure doesn't stop the unit.
2. [Service] Section
Used only for .service units.
Defines how the service runs, what command starts it, and how systemd supervises it.
Common directives:
[Service]
Type=simple
ExecStart=/usr/bin/myapp --option
ExecStop=/usr/bin/myapp --stop
ExecReload=/usr/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=3
User=myuser
Group=mygroup
WorkingDirectory=/opt/myapp/
Environment="ENV=prod"
Key parameters:
-
Type=
-
simple: default, runs and stays running. -
forking: service daemonizes (like old SysV daemons). -
oneshot: runs a single task and exits. -
notify: service notifies systemd when ready.
-
-
ExecStart: required; the command to start the service.
-
ExecStop: optional; command to stop it gracefully.
-
Restart: auto-restart options (
always,on-failure, etc.). -
User/Group: run service as non-root.
-
Environment: environment variables.
3. [Install] Section
Defines how the unit integrates into the system when using systemctl enable.
[Install]
WantedBy=multi-user.target
Alias=myapp.service
RequiredBy=network.target
Meaning:
-
WantedBy: which target this service should start with.
-
RequiredBy: hard dependency from another target.
-
Alias: alternative name.
When you run:
systemctl enable myapp.service
systemd creates symlinks based on the WantedBy or RequiredBy values.
Complete Example Unit File
[Unit]
Description=My Custom Web Service
Documentation=https://docs.example.com/myservice
After=network.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/webapp/server.py
Restart=always
RestartSec=5
User=webuser
WorkingDirectory=/opt/webapp
Environment="ENV=production"
[Install]
WantedBy=multi-user.target
Summary of Unit File Sections
| Section | Purpose |
|---|---|
| [Unit] | Metadata and dependencies |
| [Service] | How the service starts, runs, and restarts (services only) |
| [Install] | Integration with boot targets (systemctl enable) |