开机自启相关.md 2.3 KB

使用 systemctl 配置服务.并且使其自启动

新增服务

[!note] ubuntu 21.04

定义服务

/lib/systemd/system/ 目录下创建文件 serverName.service

[!warning] serverName 替换为自己需要的服务名称,可以直接执行下面的代码

修改文件,使用vim来进行编辑, 在shell

vim /lib/systemd/system/serverName.service

通过vim打开serverName.service后继续输入下方代码,其中的 server 替换成执行任务

[Unit]
Description=fraps service
After=network.target network-online.target syslog.target
Wants=network.target network-online.target
[Service]
Type=simple
#要启动的命令(此处根据实际情况填写)
ExecStart= #server 执行的任务,此注释替换新的
[Install]
WantedBy=multi-user.target

启用服务

sudo systemctl enable serverName

启动服务进程

sudo systemctl start serverName

常用命令

[!tip] 常用命令基本上分为 start restart stop

启动服务进程

sudo systemctl start serverName

重启服务

sudo systemctl restart serverName

关闭服务

sudo systemctl stop serverName

启用服务

sudo systemctl enable serverName

停用服务

sudo systemctl disable serverName

问题解决

[!warning] 如果重新修改了服务文件需要执行systemctl daemon-reload重新加载 Warning: The unit file, source configuration file or drop-ins of githook.service changed on disk. Run > 'systemctl daemon-reload' to reload units.

  systemctl daemon-reload

日志查看

[!tip] 查看服务日志使用 journalctl -u 服务名 journalctl用来查看systemctl搜集到的日志,可以用来调试排查问题. 据说是systemctl携带的

使用示例

查看服务名为githook的服务日志

journalctl -u githook.service

更多使用技巧

  1. 查看最近的日志

携带参数n加数字可以看到最近n条日志

代码示例

journalctl -n 100 -u githook.service