systemd is now used for user sessions. System sessions had already been provided by systemd in previous Ubuntu releases.
Ubuntu-18.04用 systemctl 命令来替换了 service 和 chkconfig 的功能。
比如以前启动mysql服务,命令为:
service mysql start
在Ubuntu-18.04启动mysql服务的命令则是:
systemctl start mysqld.service
systemd 默认读取 /etc/systemd/system 下的配置文件,该目录下的文件会链接/lib/systemd/system/下的文件。执行 ls /lib/systemd/system 你可以看到有很多启动脚本,其中就有我们需要的 rc.local.service。
打开rc.local.service脚本中的内容如下所示:
[Unit]
Description=/etc/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.local start
ExecStop=/etc/rc.local stop
ExecReload=/etc/rc.local restart
TimeoutSec=0
RemainAfterExit=yes
启动脚本的组成
一般启动脚本的由三个部分组成:
[Unit] 段: 主要是对这个服务的说明,内容包括Description和After。Description 用于描述服务,After用于描述服务类别。
[Service] 段: 是服务的一些具体运行参数的设置。
Type=forking是后台运行的形式,
User=users是设置服务运行的用户,
Group=users是设置服务运行的用户组,
PIDFile为存放PID的文件路径,
ExecStart为服务的具体运行命令,
ExecReload为重启命令,
ExecStop为停止命令,
PrivateTmp=True表示给服务分配独立的临时空间
注意:[Service]部分的启动、重启、停止命令全部要求使用绝对路径,使用相对路径则会报错!
[Install] 段: 服务安装的相关设置,即怎样做到开机启动。可设置为多用户的。
开机启动服务注册步骤
- 从脚本中可以看出,/etc/rc.local 的启动顺序是在网络后面,但是显然它少了 Install 段,也就没有定义如何做到开机启动,所以显然这样配置是无效的。 因此我们就需要在后面帮他加上 [Install] 段:
[Install]
WantedBy=multi-user.target
- 需要注意一下,ubuntu-18.04 默认是没有 /etc/rc.local这个文件的,需要自己创建。把需要启动的脚本放在/etc/rc.local中,此处作为测试,仅放入一段测试脚本。
touch /etc/rc.local //创建rc.local
vi /etc/rc.local
//启动脚本的内容
#!/bin/sh -e
echo "看到这行字,说明添加自启动脚本成功。" > /usr/local/test.log
exit 0
chmod +x /etc/rc.local
- 做完这一步,还需要最后一步 前面我们说 systemd 默认读取 /etc/systemd/system 下的配置文件, 所以还需要在 /etc/systemd/system 目录下创建软链接
ln -s /lib/systemd/system/rc.local.service /etc/systemd/system/
- 接下来,重启系统,然后看看 /usr/local/text.log 文件是否存在就知道开机脚本是否生效了。
附录
以rc.local.service为例,介绍部分systemctl命令
- 从服务角度
systemctl start rc.local.service #启动服务
systemctl stop rc.local.service #停止服务
systemctl restart rc.local.service #重启服务
systemctl status rc.local.service #查看服务当前状态
systemctl is-active rc.local.service #查看服务是否处于启动状态
systemctl daemon-reload //修改脚本后重新加载
systemctl enabled rc.local.service #设置为开机自动启动
systemctl disabled rc.local.service #设置为开机禁用
systemctl list-units --type=service #显示所有已经启动的服务
关于service文件里的一些选项,参考
http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-part-two.html