Systemd is a system and service manager for Linux operating systems. It is designed to be backwards compatible with SysV init scripts, and provides a number of features such as parallel startup of system services at boot time, on-demand activation of daemons, or dependency-based service control logic. In simple words , It provides a system and service manager that runs as PID 1 and starts the rest of the system.
Get Varun Ladha’s stories in your inbox
Join Medium for free to get updates from this writer.
Practical example to understand it
- Create app.py at /opt/systemd-learning-project/
from http.server import HTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b"Learning Systemd")
server = HTTPServer(("0.0.0.0", 8080), Handler)
server.serve_forever()- Check it is working .
- Now create systemd file .
sudo nano /etc/systemd/system/systemd-learning-project.service[Unit]
Description=Learning Systemd Application
After=network.target
[Service]
User=devops
WorkingDirectory=/opt/systemd-learning-project
ExecStart=/usr/bin/python3 /opt/systemd-learning-project/app.py
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target- Create new User devops and give it access ,it is not necessary you can set your own user in User= in unit file .
sudo useradd --system --no-create-home devops
sudo chown -R devops:devops /opt/myapp/opt/systemd-learning-project- Let the systemd know the new service
sudo systemctl daemon-reload
sudo systemctl start systemd-learning-project.service
sudo systemctl status systemd-learning-project.service. We can also start this with normal server boot .
sudo systemctl enable systemd-learning-projectNow let us intentionally make service crash.
- Change app.py content
import time
print("Application starting...")
time.sleep(10)
print("Application crashing!")
raise Exception("Intentional test failure")- Let the systemd now the changes
sudo systemctl restart systemd-learning-project.service
sudo systemctl status systemd-learning-project.service- Check logs the application is starting after every 5 second because of configuration in unit file .(Restart=on-failure
RestartSec=5 )
sudo journalctl -u myapp -f- Remove that configuration and check the service restarting . The service will not restart by itself .
Links to Learn :
- Basic Systemctl Commands : https://youtu.be/--w38cgP3kY?si=98oVIS3GjD1LkEcY








