Remember, most of these commands need authentication, so you'll probably need to run these commands with sudo
Start a service: systemctl start xyz.service
Stop a service: systemctl stop xyz.service
Restart a service: systemctl restart xyz.service
Status of service: systemctl status xyz.service
Status of service - Get last 50 lines, full line length: systemctl status xyz.service -n 50 -l
Track the output of a service: journalctl -u xyz.service -f -l
Typical unit file location: /etc/systemd/system
Reload unit files (do this after editing a unit file!): systemctl daemon-reload
Enable a unit file to run on startup: systemctl enable xyz.service
Disable a unit file to run on startup: systemctl disable xyz.service
List running services: systemctl list-units --type=service --state=active
List enabled (start on boot) service files: systemctl list-unit-files | grep enabled
I create service files so much now, I'd prefer coming here for a basic template instead of Googling it all the time!
[Unit]
Description=App Title
After=network.target
[Service]
Type=simple
User=usernamehere
WorkingDirectory=/home/username/directory/
ExecStart=/bin/bash /home/username/directory/run.sh
[Install]
WantedBy=multi-user.target
Let's look at an example Minecraft server unit file:
# Install into a file like this: /etc/systemd/system/minecraftBedrock.service
# Manual run: systemctl start minecraftBedrock
[Unit]
Description=MineCraft Bedrock Server
After=network.target
OnFailure=status-email-user@%n.service
[Service]
Type=simple
User=username
WorkingDirectory=/home/username/minecraft/bedrock/
ExecStart=/bin/bash /home/username/minecraft/bedrock/start.sh
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
See the OnFailure
line? This triggers the failure email. Let's create a new service to be triggered on a service failure (replace youraddress@gmail.com
with an actual email address and username
with your actual username):
# Install into a file like this: /etc/systemd/system/status-email-user@.service
[Unit]
Description=status email for %i to alarms
[Service]
Type=oneshot
ExecStart=/bin/bash /usr/local/bin/systemd-email youraddress@gmail.com %i
User=username
Group=systemd-journal
This service also requires a command be added to your bin:
# Install into a file like this: /usr/local/bin/systemd-email
#!/bin/bash
#/usr/sbin/sendmail -t <<ERRMAIL
ssmtp -vvv $1 <<ERRMAIL
To: $1
From: systemd <root@$HOSTNAME>
Subject: $2
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset=UTF-8
$(systemctl status --full "$2")
ERRMAIL
Just to be safe, it's probably good to run the following:
sudo chmod +x /usr/local/bin/systemd-email
sudo chown username /usr/local/bin/systemd-email
This script uses ssmtp
. If you don't have that package, a quick sudo apt install ssmtp
should fix that.