systemd服务开机自启必须用systemctl enable并配好service文件,不能依赖rc.local;需确保[Install]段、Type类型、绝对路径、权限正确,且通过is-enabled和status排查失效原因。

systemd 服务开机自启必须用 systemctl enable,不是改 rc.local
现在主流发行版(Ubuntu 16.04+、CentOS 7+、Debian 8+)默认用 systemd 管理启动,/etc/rc.local 默认不执行或被禁用。直接往里加 ./myapp & 很可能没反应,连日志都看不到。
正确做法是写一个 service 文件,再用 systemctl enable 注册进启动链:
-
/etc/systemd/system/myapp.service必须有[Install]段,且含WantedBy=multi-user.target - service 文件里
Type=要匹配实际行为:脚本用Type=simple(默认),后台常驻进程建议Type=forking并配PIDFile= - 路径务必写绝对路径:
ExecStart=/opt/myapp/bin/start.sh,不能用~/或./ - 权限要设对:service 文件属主 root:root,权限
644;启动脚本至少755
systemctl enable 后没生效?先查 systemctl is-enabled 和 systemctl status
systemctl enable 只是创建软链接(比如 /etc/systemd/system/multi-user.target.wants/myapp.service),不验证内容是否合法。常见失效原因:
-
systemctl is-enabled myapp返回disabled→ service 文件名拼错,或[Install]段缺失/格式错误 -
systemctl status myapp显示inactive (dead)且Loaded:行末标bad→ service 文件语法错误,比如漏了=或用了中文冒号 - 重启后没起来,但手动
systemctl start myapp成功 → 可能依赖未就绪,加After=network.target或Wants=network.target
非 systemd 场景:Ubuntu 22.04+ 的 rc.local 需手动激活
即使你坚持用 rc.local(比如兼容旧脚本),它在新版 Ubuntu 里默认是 disabled 的,不是“写了就能跑”:
- 先确认
/etc/rc.local存在且可执行:chmod +x /etc/rc.local - 运行
systemctl enable rc-local(注意是rc-local,不是rc.local) - 检查
systemctl status rc-local是否 active,否则看报错——常见是/bin/bash路径不对,或脚本里用了未安装的命令 - 别在
rc.local里用su -u user -c "cmd"启动服务,容易因环境变量缺失失败;改用sudo -i -u user bash -c 'cmd'
开机自启失败时最该看的三处日志
别只盯着 journalctl -u myapp,很多问题根本没走到 service 那步:
- 服务加载阶段失败:
journalctl --system --since today | grep -i "myapp\|failed to load" - 启动时崩溃:
journalctl -b -u myapp(-b表示本次 boot) - systemd 自身依赖问题:
systemctl list-dependencies --reverse myapp,看它等哪些 target,再查那些 target 是否 active
真正卡住的地方,往往是 service 文件里漏了 User= 导致以 root 身份读不到普通用户家目录下的配置,或者 WorkingDirectory= 没设,导致相对路径全崩。










