Problem Statement
Explain systemd service management including creating custom service units, service dependencies, and troubleshooting service failures.
Explanation
Systemd service units defined in /etc/systemd/system/ (custom) or /lib/systemd/system/ (packaged). Unit file format has [Unit], [Service], and [Install] sections. Example: [Unit] Description=My Service, After=network.target ensures service starts after network. [Service] Type=simple, User=appuser, ExecStart=/path/to/binary, Restart=on-failure. [Install] WantedBy=multi-user.target enables with systemctl enable.
Service types: simple (default, main process specified by ExecStart), forking (service forks background process), oneshot (process expected to exit, good for scripts), notify (service sends notification when ready), idle (delays execution until other jobs finish). Choose type based on application behavior. ExecStartPre and ExecStartPost run commands before/after main process.
Dependencies and ordering: Wants= suggests dependencies (service starts even if dependency fails), Requires= enforces dependencies (service fails if dependency fails), After=/Before= controls ordering without enforcing dependencies. Example: After=postgresql.service Requires=postgresql.service ensures database starts first and is required. Conflicts= prevents services from running simultaneously.
Troubleshooting: systemctl status service shows current state and recent logs. Journalctl -u service shows full logs, journalctl -u service -f follows logs live, journalctl -u service --since "1 hour ago" filters by time. Check service file syntax: systemd-analyze verify service.service. View dependencies: systemctl list-dependencies service. Test configuration: systemctl daemon-reload reloads after editing units.
Common issues: service fails immediately (check ExecStart path and permissions), service times out starting (increase TimeoutStartSec or fix slow startup), service restarts repeatedly (check Restart= setting and logs for crash cause), service doesn't start at boot (check WantedBy= and systemctl enable status), environment variables not set (use Environment= or EnvironmentFile=). Create minimal test service to isolate issues. Understanding systemd is crucial for managing services in modern Linux environments.