Unit Files
Last edited
Unit files
Unit and service definition
Pithy
Unit: a declarative description of a managed thing
Service: the thing that is running
A similar relationship/abstraction to a program and a process
Unit file locations
# Main
/usr/lib/systemd/system
/lib/systemd/system # some systems
# Custom unit files
/etc/systemd/system
/run/systemd/system Unit file format
custom.service
# /etc/systemd/system/custom.service
# Unit section optional for metadata
[Unit]
Description=Test Service
# Service section is the actual config for what the service does
[Service]
# How the service tells the manager that startup has finished
Type=oneshot
# Actual command to run
ExecStart=/bin/echo "hello from custom.service"
# Install section says what to do if the service is "enabled" (auto-start)
[Install]
# Creates a symlink in multi-user.target.wants/ that points to my service
# multi-user.target is like a checkpoint that certain services have been started
# so once it hits that checkpoint my service is started (if enabled).
# This doesn't affect if the service is run manually with "start".
WantedBy=multi-user.targetUnit file examples
sshd
sshd is poorly packaged in debian/ubuntu as ssh - try to ignore this as it means sshd and is separate from the ssh binary.
I will omit the less interesting parts of the unit. See the above man pages (man 5 systemd.unit)
ssh.service
#/etc/lib/systemd/system/ssh.service
[Unit]
# Once network manager is started (not connected) https://systemd.io/NETWORK_ONLINE/
# and audit logging deamon is up
After=network.target auditd.service
# if you create the following file: /etc/ssh/sshd_not_to_be_run
# ssh service will refuse to start with any of the systemctl start commands:
# start, restart, enable --now
# This is like the WannaCry dns kill switch
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run
# TODO! Continue
[Service]
EnvironmentFile=-/etc/default/ssh
ExecStartPre=/usr/sbin/sshd -t
ExecStart=/usr/sbin/sshd -D $SSHD_OPTS
ExecReload=/usr/sbin/sshd -t
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartPreventExitStatus=255
Type=notify
RuntimeDirectory=sshd
RuntimeDirectoryMode=0755
[Install]
WantedBy=multi-user.target
# Aliased to sshd to ease of administration
Alias=sshd.serviceDocumentation
Bash
man 5 systemd.unit # [Unit] and [Install] sections — common to all unit types
man 5 systemd.service # [Service] section
man 5 systemd.exec # execution environment (User=, WorkingDirectory=, Environment=, etc.)
man 5 systemd.kill # how processes are killed (KillMode=, KillSignal=, etc.)
man 5 systemd.resource-control # resource limits (CPUQuota=, MemoryLimit=, etc.)
man 7 systemd.syntax # the unit file syntax/format rules
man 1 systemctl # the CLI to manage units