Creating your first systemd service

Systemd is at the time of writing this article is the de-facto init system for Linux. Systemd has three primary aspect:

  1. System and service manager
  2. Software platform for developing other applications
  3. “Glue” between the kernel and user applications

Units

Systemd manages units. Units have dependency and systemd handles that dependency. Location of unit file paths:

  • /lib/systemd/system :; for package-installed units
  • /etc/systemd/system :: for administrator-configured units
  • /run/gystemd/system :; for non-persistent runtime modification

Unit files are named in following convention name.type. For example: ssh.socket, example.service. The unit file follows toml like syntax.

[Unit]
Description=Consul
Requires=network-online.target
After=network-online.target

[Service]
Restart=on-failure
ExecStart=/usr/local/bin/example 
ExecReload=/bin/kill -HUP $MAINPID
killSignal=SIGTERM
User=consul
Group=consul

[Install]
WantedBy=mulit-user.target

Service Unit Types

  • Simple (default):: for executables which run without daemonising
  • Forking:: for executables which daemonise themselves
  • Oneshot:; ususally short lived programs which run to completion and terminate
  • Notify:; for executables which will notify systemd when htey are started and available for works

Unit commands

  • systemctl enable example.service :: starts at boot
  • systemctl start example.service
  • systemctl stop example.service
  • systemctl restart example.service
  • systemctl status consul.service

Drop-in Configuration

Modification of default service configuration can be done through following location /etc/systemd/system/example.service.d/example.conf. We can use systemd-delta command to see final configuration of unit file of any service.

Common Bootstrapping Pattern

  • Install software from a generic package
  • Install bootstrapping script and drop-in configuration an environment-specific package.

Target Units

Replacement for runlevel. Targets is reached when all the services are started successfully.

Socket Units

Enables separating service and socket. Socket does not need to die when service die.

Timer Units

Some kind of replacement for corn.

Example service

[Unit]
Description="example script/service that needs to be run"

[Service]
Type=oneshot
ExecStart="bash example.sh"

Timer service

[Unit]
Description="run example.service every 10 minutes"

[Timer]
OnCalendar:*:0/10
comments powered by Disqus