Services and systemd
Table of contents
- Introduction to systemd
- systemctl: essential commands
- Enable/disable at boot
- Logs with journalctl
- Creating a simple service
- 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
| Term | Description |
|---|---|
| Unit | A resource managed by systemd |
| Service | A type of unit (daemon) |
| Target | A group of units (e.g. multi-user.target) |
| Socket | Inter-process communication |
| Timer | The modern equivalent of cron |
Unit types
| Extension | Type |
|---|---|
.service | Services/daemons |
.socket | Sockets |
.target | Groups of units |
.timer | Scheduled tasks |
.mount | Mount points |
.device | Devices |
File locations
| Path | Description |
|---|---|
/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
| Command | Description |
|---|---|
systemctl start | Start a service |
systemctl stop | Stop a service |
systemctl restart | Restart |
systemctl reload | Reload the configuration |
systemctl status | View 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
| Action | Effect |
|---|---|
enable | Starts automatically at boot |
disable | Does not start at boot |
start | Starts now |
stop | Stops now |
note
enable ≠ start! 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
| Level | Meaning |
|---|---|
| 0 | emerg |
| 1 | alert |
| 2 | crit |
| 3 | err |
| 4 | warning |
| 5 | notice |
| 6 | info |
| 7 | debug |
# 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
| Section | Content |
|---|---|
| [Unit] | Metadata, dependencies |
| [Service] | Service configuration |
| [Install] | When to enable the service |
Common options
[Unit]
| Option | Description |
|---|---|
Description | Description of the service |
After | Start after these units |
Requires | Mandatory dependencies |
Wants | Optional dependencies |
[Service]
| Option | Description |
|---|---|
Type | simple, forking, oneshot... |
ExecStart | Start command |
ExecStop | Stop command |
ExecReload | Reload command |
User | Execution user |
WorkingDirectory | Working directory |
Restart | always, on-failure, no |
RestartSec | Delay before restart |
Environment | Environment 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
systemctlmanages services (start, stop, restart, status)enable= at boot,start= nowjournalctl -u service= service logsjournalctl -f= logs in real time- Custom services in
/etc/systemd/system/ - Always
daemon-reloadafter a change systemctl statusto diagnose