1 ubuntu18.04后启动的原理变更
ubuntu-16.10 开始不再使用initd管理系统,改用systemd,systemd 就是用 systemctl 命令来替换了 service 和 chkconfig 的功能。
以前启动 XXX服务用命令:
sudo service XXX start
现在改用:
sudo systemctl start XXX.service
开机启动比以前复杂一些。systemd 默认是读取 /etc/systemd/system 下的配置文件,该目录下的文件会链接/lib/systemd/system/下的文件。执行 ls /lib/systemd/system 你可以看到有很多启动脚本,其中就有我们需要的 rc.local.service。
打开该脚本,默认内容如下:
# This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
该配置文件主要分为3个部分:
- [Unit] 段: 启动顺序与依赖关系
- [Service] 段: 启动行为,如何启动,启动类型
- [Install] 段: 定义如何安装这个配置文件,即怎样做到开机启动
可以看到,默认的配置文件中少了 Install 段,也就没有定义如何做到开机启动,所以显然这样配置是无效的。 因此我们的思路就是在后面帮他加上 [Install] 段。之后在rc.local中添加启动脚本相关信息,调试后重启 测试即可。
2 设置开机启动脚本流程
@1 添加install字段
默认配置文件为:
# This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
添加install字段,添加后,配置文件为:
[Unit]
Description=/etc/rc.local Compatibility
Documentation=man:systemd-rc-local-generator(8)
ConditionFileIsExecutable=/etc/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no
[Install]
WantedBy=multi-user.target
Alias=rc-local.service
@2 之后编辑文件/etc/rc.local (没有则创建)
把你需要启动脚本写入 /etc/rc.local ,如下所示:
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
echo "log test" > /usr/local/test.log
#添加需要开机启动的脚本命令集合
exit 0
之后 添加权限,如下所示:
sudo chmod +x /etc/rc.local
@3 创建软链接
systemd 默认读取 /etc/systemd/system 下的配置文件, 所以还需要在 /etc/systemd/system 目录下创建软链接,如下所示:
ln -s /lib/systemd/system/rc.local.service /etc/systemd/system/
@4 重启系统测试开机脚本是否生效
可以通过打印日志的方式,比如:
echo "test log..." > /usr/local/test.log
也可以直接看执行结果。