/how-to-create-systemd-service-unit-in-linux

SYSTEMD

systemd uses its own .service files (units with the .service suffix)

[Unit]: this section contains information not specifically related to the type of the unit, such as the;
service description

[Unit]
Description=The Apache HTTP Server

the After option, we can state that our unit should be started after the units we provide;

After=network.target remote-fs.target nss-lookup.target httpd-init.service

start the service unit httpd.service only after the network, remove-fs, nss-lookup targets and the httpd-init service

dependencies can be declared by using the Requires option;

Requires=avahi-daemon.socket

list "soft" dependencies by using the Wants option;

Wants=docker-storage-setup.service

[Service] section of a service unit: contains information about the specific type of the unit, we can specify things as the command to be executed when the service is started

[Service]
ExecStart=/usr/sbin/NetworkManager --no-daemon

The command to be executed when a service starts, is declared by using the ExecStart option, declare commands to be executed before and after the service is started, by using the ExecStartPre and ExecStartPost options respectively.

[Install]: This section contains information about the installation of the unit; we can use options related to the service installation.

[Install]
WantedBy=multi-user.target

Sample <service>.service file: (ethtool.service)
Save in : /usr/lib/systemd/system and /etc/systemd/system

[Unit]
Description=Force ens5f5 ethernet interface to 100Mbps
Requires=Network.target
After=Network.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/sbin/ethtool -s ens5f5 wol d
ExecStop=/usr/sbin/ethtool -s ens5f5 wol g

[Install]
WantedBy=multi-user.target

Install the service we will copy the file into the /etc/systemd/system directory as ethtools.service, than we will start it:

$ sudo cp ethtools.service /etc/systemd/system && sudo systemctl start ethtools.service

verify the service is active, with the following command:

$ systemctl is-active ethtools.service
active

Source

Add comment


Security code
Refresh