精华
Linux创建systemd启动项实现开机自启动
以下所有操作都需要root权限,请使用sudo -i。
创建如下文件:
/etc/systemd/system/myservice.service
内容:
[Unit]
Description=my service
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
User=root
ExecStart=/path-to/myservice.sh
[Install]
WantedBy=multi-user.target
/path-to/myservice.sh是要运行的程序,它需要一直保持运行,不会退出。如果/path-to/myservice.sh退出,systemd会以1秒一次的频率不断重启/path-to/myservice.sh。
如果你的/path-to/myservice.sh在运行完成后会退出,不需要自动重启,请把Restart=always改成Restart=no。
After=network.target表示联网后才会启动这个服务。如果你需要联网前启动,可以删掉。
然后启动:
systemctl start myservice
设为开机自启动:
systemctl enable myservice
查看运行状态:
systemctl status myservice
查看日志:
journalctl -u myservice
修改myservice.service后,刷新systemd守护进程使修改生效:
systemctl daemon-reload
停止服务:
systemctl stop myservice
取消开机自启动:
systemctl disable myservice
删除服务:
rm /etc/systemd/system/myservice.service


