Linux System Administration

Services with systemd

35 min

systemd starts the system and supervises long-running programs (services). It restarts them when they crash and starts them at boot.

Controlling services

systemctl status nginx
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx          # re-read config without dropping connections
sudo systemctl enable --now nginx    # start now AND at boot
systemctl is-enabled nginx
systemctl list-units --type=service --state=running

Running your own app as a service

/etc/systemd/system/pandadev.service:

[Unit]
Description=PandaDev web app
After=network-online.target postgresql.service
Wants=network-online.target

[Service]
User=pandadev
Group=pandadev
WorkingDirectory=/srv/pandadev/app
EnvironmentFile=/srv/pandadev/.env
ExecStart=/srv/pandadev/.venv/bin/gunicorn wsgi:app -c gunicorn.conf.py
Restart=on-failure
RestartSec=5

# hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/srv/pandadev/uploads /srv/pandadev/logs

[Install]
WantedBy=multi-user.target
sudo chmod 600 /srv/pandadev/.env
sudo systemctl daemon-reload          # after creating or editing unit files
sudo systemctl enable --now pandadev

The hardening lines cost nothing and limit what a compromised app can do: it cannot gain privileges, cannot write outside the listed paths and cannot read users' home folders. systemd-analyze security pandadev scores how well a service is sandboxed.

Timers: scheduled jobs with logs

A timer is a modern alternative to cron, with logging and catch-up after downtime.

/etc/systemd/system/backup.service:

[Unit]
Description=Nightly database backup

[Service]
Type=oneshot
User=postgres
ExecStart=/usr/local/bin/pg-backup.sh

/etc/systemd/system/backup.timer:

[Unit]
Description=Run backup nightly

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true

[Install]
WantedBy=timers.target
sudo systemctl enable --now backup.timer
systemctl list-timers

Persistent=true runs a missed job after the machine was off at 02:30.

Check yourself

  • What is the difference between restart and reload?
  • What must you run after editing a unit file?
  • Name three hardening options and what they prevent.

Tu progreso se guarda solo en este navegador.

Enviar para revisión (10 puntos)