Systemd & Services
In a DevOps environment, you rarely run applications manually. Instead, you manage them as Services (background processes) that start automatically on boot and restart if they fail.
1. What is Systemd?
systemd is the system and service manager for most modern Linux distributions (Ubuntu, CentOS, RHEL). It is the first process that starts (PID 1) and is responsible for bringing the rest of the system up.
Service Life Cycle
A service managed by systemd can be in several states:
- Loaded: The unit configuration file has been processed.
- Active (Running): The service is currently running.
- Active (Exited): The service performed a one-time task and finished successfully.
- Inactive: The service is not running.
- Enabled: The service is configured to start automatically on boot.
- Disabled: The service will not start on boot.
2. Managing Services with systemctl
systemctl is the primary tool for controlling the systemd system and service manager.
Common Commands
| Command | Action |
|---|---|
sudo systemctl start <name> | Start a service immediately. |
sudo systemctl stop <name> | Stop a running service. |
sudo systemctl restart <name> | Stop and then start a service. |
sudo systemctl status <name> | View the current state and recent logs of a service. |
sudo systemctl enable <name> | Configure the service to start at boot. |
sudo systemctl disable <name> | Prevent the service from starting at boot. |
sudo systemctl daemon-reload | Reload systemd to pick up changes in unit files. |
# Example: Restarting the Nginx web server
sudo systemctl restart nginx3. Viewing Logs with journalctl
systemd has its own centralized logging system called the Journal.
journalctl -u <name>: View logs for a specific service unit.journalctl -f: Follow logs in real-time (liketail -f).journalctl --since "1 hour ago": View logs from a specific timeframe.journalctl -xe: View the end of the journal with extra explanations (great for debugging start failures).
Summary Matrix
| Task | Command |
|---|---|
| Check if running | systemctl status <name> |
| Set auto-start | systemctl enable <name> |
| Debug failure | journalctl -u <name> -xe |
| List all services | systemctl list-units --type=service |
[!TIP] Check Status First! Before restarting a service, always run
systemctl status <name>. It often gives you a clear hint (like a syntax error in a config file) about why a service is failing.