Add a Startup Program on Ubuntu - Systemd File Service

给 Ubuntu 添加开机自启动程序,让程序开机启动

A Demo systemd Service

The service program.

$ cat /data/abc/pointless.sh
#!/bin/bash

while true
do
    echo The current time is $(date)
    sleep 1
done

The .service file pointless.service

$ sudo vim /etc/systemd/system/pointless.service
[Service]
ExecStart=/data/abc/pointless.sh

Start and control the service

$  sudo systemctl start pointless.service
$  sudo systemctl status pointless.service

$ sudo journalctl -u pointless
Mar 06 21:45:24 pointless.sh[1090034]: The current time is Sun 06 Mar 2022 09:45:24 PM CST
Mar 06 21:45:25 pointless.sh[1090034]: The current time is Sun 06 Mar 2022 09:45:25 PM CST
Mar 06 21:45:26 pointless.sh[1090034]: The current time is Sun 06 Mar 2022 09:45:26 PM CST
Mar 06 21:45:27 pointless.sh[1090034]: The current time is Sun 06 Mar 2022 09:45:27 PM CST

$  sudo journalctl -u pointless -f

$ sudo systemctl stop pointless


$ man systemd.service

$ sudo systemctl enable pointless
Created symlink /etc/systemd/system/multi-user.target.wants/pointless.service → /etc/systemd/system/pointless.service.

$ sudo systemctl disable pointless

View Status/Logs

# See if running, uptime, view latest logs
sudo systemctl status
sudo systemctl status my_service
# Or for a user service
systemctl --user status my_service

# See all systemd logs
sudo journalctl

# Tail logs
sudo journalctl -f

# Show logs for specific service
sudo journalctl -u my_daemon
# For user service
journalctl --user-unit my_user_daemon

A full version of .service file

sudo vim pointless.service

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

[Service]
ExecStart=/data/abc/pointless.sh
Restart=always
WorkingDirectory=/data/abc
User=ubuntu
User=ubuntu
Environment=GOPATH=/home/ubuntu/go

# auto start with system
[Install]
WantedBy=multi-user.target

Problem: Can not Get Env Variables

The environment variables can not be get in .service file, they must be specified the the .service file, like this

[Unit]
Description=abc serivce
After=network.target

[Service]
User=ubuntu
Group=ubuntu
Type=simple
Restart=always
RestartSec=5s
WorkingDirectory=/data/abc
ExecStart=/data/abc/demo
Environment=MONGODB_URL='mongodb://localhost:27017'

[Install]
WantedBy=multi-user.target

References