一、rc-local服务简介
Linux中的rc-local服务是一个开机自动启动的,调用开发人员或系统管理员编写的可执行脚本或命令的,它的启动顺序是在系统所有服务加载完成之后执行。
ubuntu20.04系统已经默认安装了rc-local.service服务,不过需要手动设置一下才可以使用。
二、配置
2.1、创建rc-local.service文件
systemctl默认读取/etc/systemd/system/下的配置文件。我们可以创建一个软连接到/lib/systemd/system/rc-local.service。
root@rshine:/etc/systemd/system# ln -s /lib/systemd/system/rc-local.service rc-local.service
root@rshine:/etc/systemd/system# ls rc-local.service
rc-local.service
root@rshine:/etc/systemd/system#
2.2、创建/etc/rc.local
开机自启动脚本,我们一般都放在这个文件中。但是Ubuntu20.04中默认没有这个文件,需要我们自己创建。
root@rshine:/etc/systemd/system# touch /etc/rc.local
root@rshine:/etc/systemd/system# chmod 755 /etc/rc.local
root@rshine:~# echo '#!/bin/bash' >> /etc/rc.local
2.3、设置rc-local.service开机自启
将rc-local.service服务设置为开机自启动。当然有可能你会遇到下面的报错。
root@rshine:/etc/systemd/system# systemctl enable rc-local.service
The unit files have no installation config (WantedBy=, RequiredBy=, Also=,
Alias= settings in the [Install] section, and DefaultInstance= for template
units). This means they are not meant to be enabled using systemctl.
Possible reasons for having this kind of units are:
• A unit may be statically enabled by being symlinked from another unit's
.wants/ or .requires/ directory.
• A unit's purpose may be to act as a helper for some other unit which has
a requirement dependency on it.
• A unit may be started when needed via activation (socket, path, timer,
D-Bus, udev, scripted systemctl call, ...).
• In case of template units, the unit is meant to be enabled with some
instance name specified.
root@rshine:/etc/systemd/system#
报错解决方法:
在/etc/systemd/system/rc-local.service文件末尾添加最后三行,如果有的话就不用添加。
root@rshine:~# cat /etc/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
[Install]
WantedBy=multi-user.target
Alias=rc-local.service
root@rshine:~#
再次设置开机自启就不会报错了。
root@rshine:/etc/systemd/system# systemctl enable rc-local.service
Created symlink /etc/systemd/system/multi-user.target.wants/rc-local.service → /lib/systemd/system/rc-local.service.
root@rshine:/etc/systemd/system#