Skip to main content

Services and systemd


Table of contents

  1. Introduction to systemd
  2. systemctl: essential commands
  3. Enable/disable at boot
  4. Logs with journalctl
  5. Creating a simple service
  6. Hands-on exercises


1 - Introduction to systemd

What is systemd?

systemd is the init system and service manager of most modern Linux distributions.

Key concepts

TermDescription
UnitA resource managed by systemd
ServiceA type of unit (daemon)
TargetA group of units (e.g. multi-user.target)
SocketInter-process communication
TimerThe modern equivalent of cron

Unit types

ExtensionType
.serviceServices/daemons
.socketSockets
.targetGroups of units
.timerScheduled tasks
.mountMount points
.deviceDevices

File locations

PathDescription
/lib/systemd/system/System units (packages)
/etc/systemd/system/Custom units (admin)
~/.config/systemd/user/User units

🔝 Back to table of contents



2 - systemctl: essential commands

Managing services

CommandDescription
systemctl startStart a service
systemctl stopStop a service
systemctl restartRestart
systemctl reloadReload the configuration
systemctl statusView the state

Practical examples

# Démarrer nginx
sudo systemctl start nginx

# Arrêter nginx
sudo systemctl stop nginx

# Redémarrer (stop + start)
sudo systemctl restart nginx

# Recharger config sans interruption
sudo systemctl reload nginx

# Redémarrer si actif
sudo systemctl try-restart nginx

View the state of a service

sudo systemctl status nginx

Typical output:

● nginx.service - A high performance web server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; preset: enabled)
Active: active (running) since Mon 2024-01-15 10:30:00 UTC; 2h ago
Docs: man:nginx(8)
Process: 1234 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; (code=exited, status=0/SUCCESS)
Main PID: 1235 (nginx)
Tasks: 3 (limit: 4096)
Memory: 8.5M
CPU: 120ms
CGroup: /system.slice/nginx.service
├─1235 "nginx: master process /usr/sbin/nginx"
├─1236 "nginx: worker process"
└─1237 "nginx: worker process"

List services

# Tous les services
systemctl list-units --type=service

# Services actifs
systemctl list-units --type=service --state=active

# Services en échec
systemctl list-units --type=service --state=failed

# Tous (y compris inactifs)
systemctl list-units --type=service --all

Check if a service is active

# Vérifie si actif
systemctl is-active nginx
# active ou inactive

# Vérifie si activé au démarrage
systemctl is-enabled nginx
# enabled ou disabled

# Vérifie si en échec
systemctl is-failed nginx

🔝 Back to table of contents



3 - Enable/disable at boot

Concepts

ActionEffect
enableStarts automatically at boot
disableDoes not start at boot
startStarts now
stopStops now
note

enablestart! Enable configures automatic startup but does not launch the service immediately.

Commands

# Activer au démarrage
sudo systemctl enable nginx

# Désactiver au démarrage
sudo systemctl disable nginx

# Activer ET démarrer
sudo systemctl enable --now nginx

# Désactiver ET arrêter
sudo systemctl disable --now nginx

Mask a service

To completely prevent a service from starting:

# Masquer (impossible à démarrer)
sudo systemctl mask nginx

# Démasquer
sudo systemctl unmask nginx

View services at boot

# Services activés
systemctl list-unit-files --type=service --state=enabled

# Services désactivés
systemctl list-unit-files --type=service --state=disabled

🔝 Back to table of contents



4 - Logs with journalctl

journalctl displays the logs managed by systemd-journald.

Basic commands

# Tous les logs (peut être très long)
journalctl

# Logs d'un service spécifique
journalctl -u nginx

# Logs depuis le dernier boot
journalctl -b

# Logs en temps réel (comme tail -f)
journalctl -f

# Logs d'un service en temps réel
journalctl -u nginx -f

Filter by time

# Depuis une date
journalctl --since "2024-01-15 10:00:00"

# Jusqu'à une date
journalctl --until "2024-01-15 12:00:00"

# Dernière heure
journalctl --since "1 hour ago"

# Aujourd'hui
journalctl --since today

# Hier
journalctl --since yesterday --until today

Filter by priority

LevelMeaning
0emerg
1alert
2crit
3err
4warning
5notice
6info
7debug
# Erreurs et plus grave
journalctl -p err

# Warnings et plus grave
journalctl -p warning

# Seulement les erreurs d'un service
journalctl -u nginx -p err

Useful options

# Dernières N lignes
journalctl -n 50

# Format JSON
journalctl -o json-pretty

# Avec détails du boot
journalctl -b -1 # Boot précédent

# Espace utilisé par les logs
journalctl --disk-usage

# Nettoyer les vieux logs
sudo journalctl --vacuum-time=7d
sudo journalctl --vacuum-size=1G

🔝 Back to table of contents



5 - Creating a simple service

Structure of a service file

[Unit]
Description=Description du service
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/app
ExecStart=/usr/bin/python3 /app/server.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Sections of the file

SectionContent
[Unit]Metadata, dependencies
[Service]Service configuration
[Install]When to enable the service

Common options

[Unit]

OptionDescription
DescriptionDescription of the service
AfterStart after these units
RequiresMandatory dependencies
WantsOptional dependencies

[Service]

OptionDescription
Typesimple, forking, oneshot...
ExecStartStart command
ExecStopStop command
ExecReloadReload command
UserExecution user
WorkingDirectoryWorking directory
Restartalways, on-failure, no
RestartSecDelay before restart
EnvironmentEnvironment variables

Complete example: Node.js application

# Créer le fichier service
sudo nano /etc/systemd/system/myapp.service
[Unit]
Description=My Node.js Application
Documentation=https://github.com/user/myapp
After=network.target

[Service]
Type=simple
User=deploy
Group=deploy
WorkingDirectory=/app/myapp
ExecStart=/usr/bin/node server.js
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
Environment=NODE_ENV=production
Environment=PORT=3000

[Install]
WantedBy=multi-user.target

Enable the service

# Recharger systemd
sudo systemctl daemon-reload

# Activer et démarrer
sudo systemctl enable --now myapp

# Vérifier
sudo systemctl status myapp

# Voir les logs
journalctl -u myapp -f

Modify an existing service

# Éditer avec override (recommandé)
sudo systemctl edit nginx
# Crée /etc/systemd/system/nginx.service.d/override.conf

# Voir la configuration complète
systemctl cat nginx

# Recharger après modification
sudo systemctl daemon-reload
sudo systemctl restart nginx

🔝 Back to table of contents



6 - Hands-on exercises

Exercise 1: Manage nginx

# 1. Installer nginx
sudo apt install nginx

# 2. Vérifier l'état
sudo systemctl status nginx

# 3. Arrêter nginx
sudo systemctl stop nginx

# 4. Vérifier qu'il est arrêté
sudo systemctl is-active nginx

# 5. Démarrer nginx
sudo systemctl start nginx

# 6. Voir les logs récents
journalctl -u nginx -n 20

Exercise 2: Create a simple service

# 1. Créer un script
sudo mkdir -p /opt/myservice
cat << 'EOF' | sudo tee /opt/myservice/app.sh
#!/bin/bash
while true; do
echo "Service running at $(date)"
sleep 30
done
EOF
sudo chmod +x /opt/myservice/app.sh

# 2. Créer le fichier service
cat << 'EOF' | sudo tee /etc/systemd/system/myservice.service
[Unit]
Description=My Test Service

[Service]
Type=simple
ExecStart=/opt/myservice/app.sh
Restart=always

[Install]
WantedBy=multi-user.target
EOF

# 3. Activer et démarrer
sudo systemctl daemon-reload
sudo systemctl enable --now myservice

# 4. Vérifier
sudo systemctl status myservice
journalctl -u myservice -f

# 5. Nettoyer
sudo systemctl disable --now myservice
sudo rm /etc/systemd/system/myservice.service
sudo rm -rf /opt/myservice
sudo systemctl daemon-reload

Quiz

Q1. How do you enable a service at boot AND launch it immediately?

Answer

sudo systemctl enable --now service

Q2. How do you view a service's logs in real time?

Answer

journalctl -u service -f

Q3. Where do you create a custom service file?

Answer

/etc/systemd/system/

🔝 Back to table of contents



Key takeaways

  • systemctl manages services (start, stop, restart, status)
  • enable = at boot, start = now
  • journalctl -u service = service logs
  • journalctl -f = logs in real time
  • Custom services in /etc/systemd/system/
  • Always daemon-reload after a change
  • systemctl status to diagnose

🔝 Back to table of contents


← Previous chapter | Next chapter: Environment variables →