| name | systemd |
| description | Systemd service management, unit files, timers, and journal logging on Linux. Use when user mentions "systemd", "systemctl", "service file", "unit file", "journalctl", "system service", "daemon", "auto-start on boot", "timer", "systemd timer", "service restart", "enable service", "journald", "system logs", or managing Linux services and daemons. |
Systemd
systemctl Commands
sudo systemctl start myapp
sudo systemctl stop myapp
sudo systemctl restart myapp
sudo systemctl reload myapp
sudo systemctl enable myapp
sudo systemctl enable --now myapp
sudo systemctl disable myapp
systemctl status myapp
systemctl is-active myapp
systemctl is-enabled myapp
systemctl show myapp -p MainPID,MemoryCurrent
sudo systemctl daemon-reload
systemctl list-units --type=service --state=failed
systemctl list-unit-files --type=service
systemctl list-timers
Writing Unit Files
Place system services in /etc/systemd/system/myapp.service.
[Unit]
Description=My Application Server
After=network.target postgresql.service
Wants=postgresql.service
[Service]
Type=simple
User=appuser
Group=appgroup
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/server
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp
[Install]
WantedBy=multi-user.target
After creating or editing: sudo systemctl daemon-reload && sudo systemctl enable --now myapp
Service Types
| Type | Behavior | Use Case |
|---|
| simple | Default. ExecStart process is the main process | Most long-running services |
| forking | Process forks; parent exits. Set PIDFile | Traditional daemons |
| oneshot | Runs and exits. Service is "active" after completion | Setup scripts, migrations |
| notify | Like simple, but sends sd_notify when ready | systemd-aware apps |
| idle | Like simple, but waits until other jobs finish | Low-priority startup tasks |
[Service]
Type=forking
PIDFile=/run/myapp/myapp.pid
ExecStart=/opt/myapp/bin/server --daemonize
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/setup-iptables.sh
Environment Variables
[Service]
Environment=NODE_ENV=production
Environment=PORT=3000 HOST=0.0.0.0
EnvironmentFile=/etc/myapp/env
EnvironmentFile=-/etc/myapp/env.local
Environment file (/etc/myapp/env): one VAR=VALUE per line.
Restart Policies
[Service]
Restart=on-failure
RestartSec=5
StartLimitIntervalSec=300
StartLimitBurst=5
| Policy | Clean exit | Unclean signal | Timeout | Watchdog |
|---|
| no | - | - | - | - |
| on-failure | - | Yes | Yes | Yes |
| on-abnormal | - | Yes | Yes | Yes |
| always | Yes | Yes | Yes | Yes |
Reset a failed unit: sudo systemctl reset-failed myapp
Resource Limits
[Service]
MemoryMax=512M
MemoryHigh=400M
CPUQuota=200%
CPUWeight=50
LimitNOFILE=65536
LimitNPROC=4096
Dependency Management
[Unit]
After=network.target redis.service
Before=nginx.service
Requires=postgresql.service
Wants=redis.service
BindsTo=docker.service
After=network-online.target
Wants=network-online.target
User Services
Place units in ~/.config/systemd/user/. No root required.
[Unit]
Description=My User Application
[Service]
Type=simple
ExecStart=%h/bin/myapp
Restart=on-failure
Environment=PORT=8080
[Install]
WantedBy=default.target
systemctl --user daemon-reload
systemctl --user enable --now myapp
journalctl --user -u myapp -f
sudo loginctl enable-linger $USER
%h expands to the user's home directory.
Timers (Cron Replacement)
[Unit]
Description=Daily backup timer
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
RandomizedDelaySec=900
[Install]
WantedBy=timers.target
[Unit]
Description=Backup job
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
Monotonic timers (relative to boot):
[Timer]
OnBootSec=5min
OnUnitActiveSec=1h
OnCalendar examples:
hourly | daily | weekly
Mon,Fri *-*-* 09:00:00 # Mon and Fri at 9 AM
*-*-01 00:00:00 # First of every month
*-*-* *:00/15:00 # Every 15 minutes
Validate: systemd-analyze calendar "Mon,Fri *-*-* 09:00:00"
journalctl Log Querying
journalctl -u myapp -f
journalctl -u myapp -n 100
journalctl -u myapp --since "1 hour ago"
journalctl -u myapp --since "2024-01-15" --until "2024-01-16"
journalctl -u myapp -p err
journalctl -u myapp -b
journalctl -u myapp -o json-pretty -n 10
journalctl -u myapp -o json --no-pager | jq '.MESSAGE'
journalctl -k
journalctl --disk-usage
sudo journalctl --vacuum-size=500M
sudo journalctl --vacuum-time=7d
Socket Activation
Start services on-demand when a connection arrives.
[Unit]
Description=My App Socket
[Socket]
ListenStream=8080
Accept=no
[Install]
WantedBy=sockets.target
[Unit]
Description=My App
Requires=myapp.socket
[Service]
Type=simple
ExecStart=/opt/myapp/bin/server
The service receives the socket as fd 3 (SD_LISTEN_FDS_START). Enable the socket, not the service: sudo systemctl enable --now myapp.socket
Templated Units
Template files use @ in the name. Instance name is %i.
[Unit]
Description=My App instance %i
After=network.target
[Service]
Type=simple
User=appuser
ExecStart=/opt/myapp/bin/server --port %i
Restart=on-failure
[Install]
WantedBy=multi-user.target
sudo systemctl enable --now myapp@8080
sudo systemctl enable --now myapp@8081
Common Service Patterns
Node.js
[Service]
Type=simple
User=nodeapp
WorkingDirectory=/opt/nodeapp
ExecStart=/usr/bin/node server.js
EnvironmentFile=/etc/nodeapp/env
Environment=NODE_ENV=production
LimitNOFILE=65536
Restart=on-failure
RestartSec=5
Python (uvicorn with venv)
[Service]
Type=simple
User=pyapp
WorkingDirectory=/opt/pyapp
ExecStart=/opt/pyapp/venv/bin/python -m uvicorn main:app --host 0.0.0.0 --port 8000
EnvironmentFile=/etc/pyapp/env
Restart=on-failure
Go Binary
[Service]
Type=simple
User=goapp
ExecStart=/usr/local/bin/goservice
EnvironmentFile=/etc/goservice/env
Restart=on-failure
LimitNOFILE=65536
Docker Container
[Unit]
After=docker.service
Requires=docker.service
[Service]
Type=simple
Restart=always
RestartSec=10
ExecStartPre=-/usr/bin/docker stop mycontainer
ExecStartPre=-/usr/bin/docker rm mycontainer
ExecStart=/usr/bin/docker run --rm --name mycontainer -p 8080:80 myimage:latest
ExecStop=/usr/bin/docker stop mycontainer
- prefix on ExecStartPre: don't fail if the command fails (container may not exist).
All patterns need [Unit] with After=network.target and [Install] with WantedBy=multi-user.target.
Debugging Failed Services
systemctl status myapp
journalctl -xeu myapp
journalctl -u myapp -b --no-pager
systemd-analyze blame
systemd-analyze critical-chain myapp
systemd-analyze verify myapp.service
systemd-analyze security myapp
systemctl show myapp -p ExecMainStatus,Result,ActiveState
Common exit codes:
- 200: bad unit file syntax (check ExecStart path, missing
=)
- 203: exec format error (missing shebang, wrong architecture)
- 217: user/group doesn't exist
Security Hardening
[Service]
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/myapp
PrivateTmp=true
NoNewPrivileges=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
SystemCallFilter=@system-service
SystemCallArchitectures=native
DynamicUser=true
StateDirectory=myapp
CacheDirectory=myapp
LogsDirectory=myapp
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
Audit: systemd-analyze security myapp (0 = most secure, 10 = least).
Path Units (File Watching)
[Unit]
Description=Watch for deployment triggers
[Path]
PathChanged=/var/deploy/trigger
PathExists=/var/deploy/run-now
PathModified=/var/deploy/config
Unit=deploy.service
[Install]
WantedBy=multi-user.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/deploy.sh
sudo systemctl enable --now deploy-watcher.path
Quick Reference: Unit File Specifiers
| Specifier | Meaning |
|---|
%i | Instance name (template units) |
%I | Unescaped instance name |
%n | Full unit name |
%h | User home directory |
%t | Runtime directory (/run) |
%S | State directory (/var/lib) |
%C | Cache directory (/var/cache) |