ubuntu-16.10 开始不再使用initd管理系统,改用systemd
执行 ls /lib/systemd/system 你可以看到有很多启动脚本,其中就有我们需要的 rc.local.service
# SPDX-License-Identifier: LGPL-2.1+
#
# 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
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
文件内容
一般正常的启动文件主要分成三部分
- [Unit] 段: 启动顺序与依赖关系
- [Service] 段: 启动行为,如何启动,启动类型
- [Install] 段: 定义如何安装这个配置文件,即怎样做到开机启动
对于Unit、Service配置不用管,我们如果自己配置开机自启动服务时候,需要配置Install配置。
[Install]
WantedBy=multi-user.target
Alias=rc-local.service
创建rc.local并授权
ubuntu-18.04 默认是没有 /etc/rc.local 这个文件的,需要自己创建,并且给该文件赋予可执行权限(否则文件不能执行,即开机不能运行,即开机自动启动会不成功)
sudo touch /etc/rc.local
chmod 755 /etc/rc.local
编辑rc.local 并测试
添加需要开机启动的任务(这里需要注意,一定要有#!/bin/bash,即指定解释此脚本的解释器shell的路径,否则未指定解释器会执行不成功)
#!/bin/bash
echo "test rc " > /usr/test.log
重启服务器reboot,此事后就会看到/var 目录下面就会有生成的test.log,说明服务自启动成功了,rc.local里面的命令得到执行
添加自己的服务,放到rc.local
#!/bin/bash
/opt/zbox/zbox start
emqx start
redis-server
现在重启reboot,自己的服务就会子机器启动时候自动启动服务了。
参考
来源:CSDN
作者:ItJavawfc
链接:https://blog.csdn.net/ItJavawfc/article/details/104222598