Alibaba Cloud Linux 4操作系统自启动配置指南

更新时间:
复制为 MD 格式

Alibaba Cloud Linux 4操作系统基于 systemd 作为 init 系统,默认不提供传统的 /etc/rc.local 自启动文件。若您需要在系统启动时自动执行自定义脚本,可参考本文创建并启用自启动配置。在下一个即将发布的 Alibaba Cloud Linux 4.0.3的版本中该问题将会被 systemd 组件修复,不需要手动再设置。

问题原因及解决方案

问题原因分析

Alibaba Cloud Linux 4等现代 Linux 发行版已从传统的 SysV init 脚本迁移至 systemd。在 systemd 体系下,不再默认提供 /etc/rc.local/etc/rc.d/rc.local 作为系统级自启动入口,因此若直接依赖该文件实现开机自启,将无法生效。

[root@iZ2zeeczb8vi6l8sot5webZ ~]# cat /etc/rc.d/init.d/README
You are looking for the traditional init scripts in /etc/rc.d/init.d,
and they are gone?
Here's an explanation on what's going on:
You are running a systemd-based OS where traditional init scripts have
been replaced by native systemd services files. Service files provide
very similar functionality to init scripts. To make use of service
files simply invoke "systemctl", which will output a list of all
currently running services (and other units). Use "systemctl
list-unit-files" to get a listing of all known unit files, including
stopped, disabled and masked ones. Use "systemctl start
foobar.service" and "systemctl stop foobar.service" to start or stop a
service, respectively. For further details, please refer to
systemctl(1).
Note that traditional init scripts continue to function on a systemd
system. An init script /etc/rc.d/init.d/foobar is implicitly mapped
into a service unit foobar.service during system initialization.
Thank you!
Further reading:
        man:systemctl(1)
        man:systemd(1)
        https://0pointer.de/blog/projects/systemd-for-admins-3.html
        https://www.freedesktop.org/wiki/Software/systemd/Incompatibilities

解决方案

可通过以下步骤手动创建 rc.local 文件并配置为 systemd 服务,使脚本在系统启动时自动执行。

1. 创建 rc.local 文件

sudo cat >/etc/rc.local <<'EOF'
#!/bin/bash
# 在此处添加您的启动命令
# 示例:
# echo "System booted at $(date)" >> /var/log/boot.log
# /usr/local/bin/my-custom-service start
exit 0
EOF

2. 设置可执行权限

chmod +x /etc/rc.local

3. 确保 systemd 的兼容性

创建 rc-local.service 单元文件,使 systemd 在 multi-user 阶段执行 /etc/rc.local

sudo cat >/etc/systemd/system/rc-local.service <<'EOF'
[Unit]
Description=/etc/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.local
After=network-online.target
Wants=network-online.target
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
StandardOutput=tty
StandardError=tty
TTYPath=/dev/tty1
[Install]
WantedBy=multi-user.target
EOF

4. 重载 systemd 配置

systemctl daemon-reload

5. 启动并启用 rc-local 服务

systemctl start rc-local
systemctl enable rc-local

完成上述步骤后,系统每次启动时会自动执行 /etc/rc.local 中的命令。

简化方式(部分环境)

问题原因分析

在部分Alibaba Cloud Linux 4或兼容环境中,若存在对 /etc/rc.d/rc.local 的兼容逻辑,仅创建该文件并赋予执行权限即可被识别为自启动脚本。

解决方案

可直接在 /etc/rc.d/ 下创建 rc.local 并赋予可执行权限,由系统默认创建或关联为相应服务:

sudo touch /etc/rc.d/rc.local
sudo chmod +x /etc/rc.d/rc.local

随后在 /etc/rc.d/rc.local 中写入需要开机执行的命令。若此方式在您的实例上未生效,请采用上文「创建 rc.local 并配置 systemd 服务」的完整步骤。