Aller au contenu principal

Services

A Service or Daemon is a program that runs in the background and activates under certain conditions. For example, the HDDTEMP service monitors the temperature of your hard drives and triggers an alert if it exceeds a certain threshold.

The service management tool (and other units elsewhere) in Systemd is called Systemctl.

Commands

Status of a service

systemctl status service_name

Start a service

systemctl start service_name

Stop a service

systemctl stop service_name

Restart a service

systemctl restart service_name

Enable a service (start at boot)

systemctl enable service_name

Disable a service

systemctl disable service_name

Recharge the configuration

systemctl daemon-reload

List all services

systemctl list-units --type=service

List all services that are currently running

systemctl list-units --type=service --state=running

Journal

To see the logs of a service, you can use the journalctl command.

journalctl -u service_name

To see the logs of a service in real time

journalctl -fu service_name

Filter the logs by date

journalctl -u service_name --since yesterday --until today

Get errors only

journalctl -u service_name -p err

Service Personalization

To create a service, you must create a file in the /etc/systemd/system/ directory with the .service extension.

[Unit]
Description=My service description
After=network.target

[Service]
ExecStart=/usr/bin/mon_script.sh
Type=simple

[Install]
WantedBy=multi-user.target
  • Section [Unit] contains metadata on the service, such as its description and its dependencies.
  • Section [Service] Specifies how the service must be executed, including the path to the executable.
  • Section [Install] Defines how the service should be activated at start -ups.

Then, you must reload the configuration

systemctl daemon-reload

And start the service

systemctl start my_service

To enable the service at boot

systemctl enable my_service

Examples

Node Application

[Unit]
Description=Example Node.js Application Description
After=network.target

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/myapp
ExecStart=/usr/bin/npm run serve -- --build --port 3000 --host 0.0.0.0
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target

Streamlit Application

[Unit]
Description=Streamlit Application Description
After=network.target

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/myapp
ExecStart=/usr/bin/streamlit run app.py --server.port 8501
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target