在 /etc/rc.d/rc.local 写入开机需要运行的命令,是在 CentOS 5/6 中常见做法。但是在CentOS 7 中,却出现了 rc.local 中命令,系统启动后却不执行的情况……
原因
rc.local
是 Sysvinit 技术用于 CentOS 5/6 的 init
进程在启动过程中最后执行的任务。但是众所周知,CentOS7和 CentOS8 是使用了 Systemd 技术启动,开机不会运行 init 进程。
为了兼容,CentOS 7 官方提供的方法是默认提供了一个名为“rc-local” 的 systemd 服务,负责系统启动后执行 rc.local 中的命令。但是有一个前提: /etc/rc.d/rc.local 必须是可执行(默认是不可执行的)。
解决
cat /etc/rc.d/rc.local
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
touch /var/lock/subsys/local
chmod a+x /etc/rc.d/rc.local
systemctl enable rc-local
systemctl start rc-local
延伸
cat /usr/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.d/rc.local is executable.
[Unit]
Description=/etc/rc.d/rc.local Compatibility
Documentation=man:systemd-rc-local-generator(8)
ConditionFileIsExecutable=/etc/rc.d/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.d/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no
照猫画虎的猫: