14. Systemd Services
systemd is the standard init system and service manager for modern Linux distributions. It initializes the user-space environment after the kernel boots and manages system daemons, timers, mounts, and dependencies throughout the machine’s lifecycle.
14.1 systemd Architecture & Units
Section titled “14.1 systemd Architecture & Units”systemd manages system resources through configuration files known as Units, stored in:
/lib/systemd/system/(or/usr/lib/systemd/system/): Default unit files installed by software packages./etc/systemd/system/: System administrator custom unit files and configuration overrides (takes precedence over/lib/).
Common Unit Types
Section titled “Common Unit Types”- Services (
.service): Manages a background daemon or application (e.g.,nginx.service,sshd.service). - Targets (
.target): Groups units to synchronize system state (e.g.,multi-user.targetfor multi-user CLI mode,graphical.targetfor desktop GUI mode). - Sockets (
.socket): Listens on a network port or IPC socket, automatically spawning the service upon receiving an incoming connection. - Timers (
.timer): Schedules recurring jobs with calendar or monotonic event triggers (modern alternative tocron). - Mounts (
.mount): Controls filesystem mount points.
14.2 Service Management with systemctl
Section titled “14.2 Service Management with systemctl”The primary utility used to interact with systemd is systemctl.
Master Service Management Reference
Section titled “Master Service Management Reference”| Task | Modern systemctl Command | Legacy SysVinit Equivalent |
||||
| Check service status | sudo systemctl status sshd | service sshd status |
| Start a service | sudo systemctl start sshd | service sshd start |
| Stop a service | sudo systemctl stop sshd | service sshd stop |
| Restart a service | sudo systemctl restart sshd | service sshd restart |
| Reload configuration | sudo systemctl reload sshd | service sshd reload |
| Enable at boot | sudo systemctl enable sshd | chkconfig sshd on |
| Disable at boot | sudo systemctl disable sshd | chkconfig sshd off |
| Enable & start together | sudo systemctl enable --now sshd | N/A |
| Check if enabled | systemctl is-enabled sshd | chkconfig --list sshd |
| Check if active | systemctl is-active sshd | service sshd status |
| List active services | systemctl list-units --type=service | service --status-all |
| List all unit files | systemctl list-unit-files --type=service | chkconfig --list |
| Mask (lock) service | sudo systemctl mask nginx | N/A |
| Unmask service | sudo systemctl unmask nginx | N/A |
| Edit service unit | sudo systemctl edit --full nginx | N/A |
| Reload systemd manager | sudo systemctl daemon-reload | N/A |
| View service logs | sudo journalctl -u sshd -f | Inspect /var/log/messages |
14.3 Advanced Operations: Masking & Custom Overrides
Section titled “14.3 Advanced Operations: Masking & Custom Overrides”1. Masking a Service
Section titled “1. Masking a Service”Disabling a service (systemctl disable) only stops it from starting automatically at boot. Another service or user can still start it manually or trigger it as a dependency.
To completely prevent a service from ever being started under any circumstances, mask it:
# Mask service (symlinks unit to /dev/null)sudo systemctl mask apache2
# Any attempt to start it will fail:# Output: Failed to start apache2.service: Unit apache2.service is masked.
# Unmask to restore normal behaviorsudo systemctl unmask apache22. Overriding Unit Settings (systemctl edit)
Section titled “2. Overriding Unit Settings (systemctl edit)”Never edit vendor files in /lib/systemd/system/ directly; package updates will overwrite your changes. Instead, use systemctl edit:
- Drop-in override:
sudo systemctl edit nginxcreates/etc/systemd/system/nginx.service.d/override.confto modify specific parameters (e.g., addingRestartSec=10). - Full copy override:
sudo systemctl edit --full nginxcopies the entire unit to/etc/systemd/system/nginx.servicefor complete customization.
14.4 Creating Custom Services
Section titled “14.4 Creating Custom Services”DevOps engineers frequently deploy custom applications (Node.js, Go, Python FastAPI) as systemd services.
Example: Production Service Unit (/etc/systemd/system/my-api.service)
Section titled “Example: Production Service Unit (/etc/systemd/system/my-api.service)”[Unit]Description=Backend Production API ServiceAfter=network.target postgresql.serviceWants=postgresql.service
[Service]Type=simpleUser=appuserGroup=appuserWorkingDirectory=/opt/my-apiExecStart=/usr/bin/python3 -m uvicorn main:app --host 0.0.0.0 --port 8000
# Environment ConfigurationEnvironment="ENV=production"EnvironmentFile=/etc/default/my-api
# Resilience & Auto-Restart PoliciesRestart=on-failureRestartSec=5sTimeoutStopSec=30s
# Resource Throttling (cgroups)MemoryMax=1GCPUQuota=80%
# Security SandboxingProtectSystem=fullPrivateTmp=trueNoNewPrivileges=true
[Install]WantedBy=multi-user.targetApplying Custom Service Changes
Section titled “Applying Custom Service Changes”# 1. Reload systemd daemon to process new/edited unit filessudo systemctl daemon-reload
# 2. Enable and start the servicesudo systemctl enable --now my-api
# 3. Check health and real-time logssudo systemctl status my-apisudo journalctl -u my-api -n 50 --no-pager14.5 Dependencies & Restart Policies
Section titled “14.5 Dependencies & Restart Policies”Dependency Directives ([Unit])
Section titled “Dependency Directives ([Unit])”After=/Before=: Controls startup order.After=network.targetmeans network initialization occurs before this service starts. (Does not enforce a hard failure if the network fails).Requires=: Hard dependency. If the required unit fails to start or crashes, this service will be stopped.Wants=: Soft dependency. Systemd attempts to start the wanted service, but continues starting this service even if the dependency fails.
Restart Policies ([Service])
Section titled “Restart Policies ([Service])”Restart=no: Default. Service will not restart if it exits.Restart=on-failure: Restarts only if the process exits with a non-zero exit code or is killed by an uncaught signal. (Standard for production apps).Restart=always: Restarts regardless of whether the exit was clean (0) or unclean.