What is systemctl?
`systemctl` is the command-line interface to **systemd**, the modern init system used by most major Linux distributions (like Ubuntu, CentOS, RHEL, Debian, Arch, Fedora).
You use `systemctl` to:
- Start and stop services
- Enable services to run at boot
- Check service status
- View logs
- Troubleshoot failures
- Manage dependencies
Real-World Example: Creating a Custom Service
Let’s say you have a Python web application that you want to run as a systemd service.
Create Your Application Directory
sudo mkdir -p /opt/mywebapp
sudo chown $USER:$USER /opt/mywebapp
Add your app file (for example, app.py) inside /opt/mywebapp/.
Create the systemd Service File
sudo nano /etc/systemd/system/mywebapp.service
Paste this configuration:
[Unit]
Description=My Python Web Application
After=network.target
[Service]
ExecStart=/usr/bin/python3 /opt/mywebapp/app.py
WorkingDirectory=/opt/mywebapp
Restart=always
RestartSec=20
User=webuser
Group=webgroup
Environment="ENV=production"
[Install]
WantedBy=multi-user.target
Explanation:
After=network.target ensures the network is up before starting.
Restart=always and RestartSec=20 ensures the app auto-recovers on failure.
User and Group ensure minimal privileges.
WantedBy=multi-user.target ensures the service starts at system boot.
Reload systemd
sudo systemctl daemon-reload
Complete systemctl Command Reference
Action Command
Start sudo systemctl start <service>
Stop sudo systemctl stop <service>
Restart sudo systemctl restart <service>
Reload sudo systemctl reload <service>
Status sudo systemctl status <service>
Enable/Disable Services at Boot
Action Command
Enable sudo systemctl enable <service>
Disable sudo systemctl disable <service>
Check Enabled systemctl is-enabled <service>
Masking Services
Action Command
Mask sudo systemctl mask <service>
Unmask sudo systemctl unmask <service>
Editing Services Safely
Action Command
Edit sudo systemctl edit <service>
Revert sudo systemctl revert <service>
List Services and Units
Action Command
Running Services systemctl list-units --type=service
All Unit Files systemctl list-unit-files
Enabled Units systemctl list-unit-files --state=enabled
View Logs (journalctl)
Action Command
View Logs journalctl -u <service>
Follow Logs journalctl -fu <service>
Today’s Logs journalctl -u <service> --since today
No comments:
Post a Comment