Linux systemd Service Files Cheat Sheet

Author, edit, override, and harden systemd .service files with practical examples.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Authoring Basics
Create custom service file
sudo nano /etc/systemd/system/myapp.service

# Open a new service file under /etc/systemd/system.

Basic service file example
[Unit]
Description=My App
After=network.target

[Service]
Type=simple
User=myapp
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node /opt/myapp/server.js
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

# Minimal custom service unit.

Reload after creating unit
sudo systemctl daemon-reload

# Refresh manager state after writing a new service.

Enable and start custom unit
sudo systemctl enable --now myapp.service

# Activate the new custom service.

## Drop-Ins and Overrides
Create override drop-in
sudo systemctl edit nginx

# Edit a unit override file.

Override environment example
[Service]
Environment=NODE_ENV=production
Environment=PORT=8080

# Set environment values in a drop-in.

Replace ExecStart in override
[Service]
ExecStart=
ExecStart=/usr/local/bin/myapp --config /etc/myapp/config.yml

# Clear old ExecStart then set new one.

Show effective unit with drop-ins
systemctl cat myapp.service

# Print final unit and all overrides.

## Environment, Users, Dependencies
Load variables from EnvironmentFile
[Service]
EnvironmentFile=/etc/myapp/myapp.env

# Use an external env file.

Run service as non-root user
[Service]
User=myapp
Group=myapp

# Specify service user and group.

Set working directory
[Service]
WorkingDirectory=/opt/myapp

# Run service from a specific directory.

Start after another unit
[Unit]
Wants=network-online.target
After=network-online.target

# Set ordering and dependency relationship.

Require another unit
[Unit]
Requires=postgresql.service
After=postgresql.service

# Fail if the required unit is absent or stopped.

## Restart Policy, Types, Hardening
Restart on failure
[Service]
Restart=on-failure
RestartSec=5

# Automatic restart policy.

One-shot service type
[Service]
Type=oneshot
ExecStart=/usr/local/bin/cleanup.sh
RemainAfterExit=yes

# Configure a one-time task service.

Use Type=notify
[Service]
Type=notify
NotifyAccess=main

# Service signals readiness to systemd.

Basic sandboxing example
[Service]
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/lib/myapp

# Apply a few common hardening options.

Limit Linux capabilities
[Service]
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE

# Reduce privilege scope.

Evaluate unit hardening
systemd-analyze security myapp.service

# Score a custom service for security posture.

More in Linux systemd Service Files

No other published sheets yet.

Recommended next

No recommendations yet.