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 作为系统级自启动入口,因此若直接依赖该文件实现开机自启,将无法生效。

解决方案
可通过以下步骤手动创建 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
EOF2. 设置可执行权限
chmod +x /etc/rc.local3. 确保 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
EOF4. 重载 systemd 配置
systemctl daemon-reload5. 启动并启用 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 服务」的完整步骤。