Manage Systemd Service

Create & Manage Systemd Service

Create a systemd service

1
sudo vi /etc/systemd/system/<service-name>.service

Add the following content to the service file (.service)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
[Unit]
Description=<service-description>
After=network.target

[Service]
Type=simple
TimeoutStartSec=30
User=<user-name>
Group=<group-name>
WorkingDirectory=<working-directory>
ExecStart=<command-to-start-service>
Restart=always
RestartSec=30s

[Install]
WantedBy=multi-user.target

Cheatsheet

Name Description Value
Description Description of the service
After The service will be started after the network is up
Type The type of service simple, forking
TimeoutStartSec The time to wait before starting the service
User The user to run the service
Group The group to run the service
WorkingDirectory The working directory of the service Eg. The source code directory.
ExecStart The command to start the service
Restart Restart the service if it crashes
RestartSec The time to wait before restarting the service
WantedBy The target to start the service

Eg. A sample service file for a Golang app

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
[Unit]
Description=Hain
Documentation=https://hainguyen.dev/

[Service]
Type=forking
User=root
Group=root
TimeoutStartSec=0
Restart=on-failure
RestartSec=30s
#ExecStartPre=
Environment=GOPATH=/root/go
WorkingDirectory=/root/go/src/github.com/hain/src
ExecStart=/bin/bash script/run.sh
SyslogIdentifier=Diskutilization
#ExecStop=

[Install]
WantedBy=multi-user.target

Enable the service

1
sudo systemctl enable <service-name>.service

Start the service

1
sudo systemctl start <service-name>.service

Stop the service

1
sudo systemctl stop <service-name>.service

Restart the service

1
sudo systemctl restart <service-name>.service

Check the service status

1
sudo systemctl status <service-name>.service

Delete the service

1
2
sudo systemctl disable <service-name>.service
sudo rm /etc/systemd/system/<service-name>.service

Troubleshooting

Check the service logs

1
sudo journalctl -u <service-name>.service

Retain the logs for a specific time

1
sudo journalctl --vacuum-time=1d

Retain the logs for a specific size

1
sudo journalctl --vacuum-size=1G

Cheatsheet

Name Description
journalctl The command to check the logs
-u The service name
-f Follow the logs
-n The number of logs to show
-o The output format
-p The priority of the logs
–vacuum-time The time to keep the logs
–vacuum-size The size to keep the logs