Skip to content

Systemd

Published: at 01:14 PM

Using systemd to handle background services in Linux.

Create a service

Unit files are located in /etc/systemd/system/

Create a systemd unit file

sudo nano /etc/systemd/system/<service_name>.service

Template

[Unit]
Description=R2D2 Images
After=network.target

[Service]
ExecStart=/home/justin/r2-images/env/bin/python /home/justin/r2-images/r2d2.py
Restart=always
User=justin
WorkingDirectory=/home/justin/r2-images

[Install]
WantedBy=multi-user.target

Commands

Check service status:

sudo systemctl status <service_name>

Example:

sudo systemctl status r2d2.service

 r2d2.service - R2D2 Images
     Loaded: loaded (/etc/systemd/system/r2d2.service; enabled; preset: enabled)
     Active: active (running) since Wed 2025-01-01 17:17:11 +07; 3 days ago
   Main PID: 1477 (python)
      Tasks: 2 (limit: 4526)
     Memory: 49.7M
        CPU: 11min 46.975s
     CGroup: /system.slice/r2d2.service
             └─1477 /home/justin/r2-images/env/bin/python /home/justin/r2-image>

Start a service:

sudo systemctl start <service_name>

Stop a service:

sudo systemctl stop <service_name>

Enable a service at boot:

By default, the service is not started. Use this command to start the service automatically at boot or when the server restarts.

sudo systemctl enable <service_name>

Disable a service at boot:

sudo systemctl disable <service_name>

Reload configuration files

Use when adding, removing or editing unit files.

sudo systemctl daemon-reload

Previous Post
Installing Postgresql