linux 服务器上部署 web 服务、node.js、java 程序之后,通常都希望服务器重启后程序能够自动恢复。
使用 systemd 的系统里,最常见的命令就是:
systemctl enable 服务名
很多人会用,但不一定清楚它到底做了什么。
1. 先确认服务是否存在
例如有一个服务:
systemctl status myapp
如果能正常看到服务状态,说明 systemd 已经识别到它。
常见的 service 文件位置有:
/etc/systemd/system/ /usr/lib/systemd/system/ /lib/systemd/system/
自己创建的服务一般放在:
/etc/systemd/system/
比如:
/etc/systemd/system/myapp.service
2. 开启开机自启动
执行:
sudo systemctl enable myapp
正常情况下会看到类似:
created symlink ...
这一步并不会自动启动当前服务。
如果希望现在就启动,还要执行:
sudo systemctl start myapp
也可以一步完成:
sudo systemctl enable --now myapp
这条命令相当于:
systemctl enable myapp systemctl start myapp
3. 怎么检查是否已经启用
执行:
systemctl is-enabled myapp
如果返回:
enabled
说明已经配置开机启动。
如果返回:
disabled
说明没有启用。
查看当前运行状态则是:
systemctl is-active myapp
这两个状态不要混淆。
一个服务完全可能出现:
enabled inactive
意思是已经设置开机启动,但现在没有运行。
4. systemctl enable 到底做了什么
systemd 的开机自启动本质上依赖符号链接。
例如 service 文件中有:
[install] wantedby=multi-user.target
执行:
systemctl enable myapp
systemd 会创建类似这样的软链接:
/etc/systemd/system/multi-user.target.wants/myapp.service
指向真正的 service 文件。
可以理解为:
系统进入 multi-user.target
↓
发现 wants 目录里的 myapp.service
↓
systemd 启动 myapp
所以 enable 本身并不是“启动程序”,而是把服务加入对应 target 的启动关系中。
5. 为什么 service 文件需要 [install]
一个常见配置:
[unit] description=my application after=network.target [service] execstart=/usr/bin/node /opt/myapp/app.js restart=always [install] wantedby=multi-user.target
这里:
[install] wantedby=multi-user.target
主要就是给 systemctl enable 使用的。
如果 service 没有 [install] 部分,执行 enable 时可能会提示:
the unit files have no installation config
这种服务可能是由其他服务依赖启动的,本身不一定适合直接 enable。
6. 取消开机启动
执行:
sudo systemctl disable myapp
这会删除之前创建的软链接。
但同样需要注意:
systemctl disable myapp
不会自动停止当前正在运行的服务。
如果还想立即停止:
sudo systemctl stop myapp
或者:
sudo systemctl disable --now myapp
7. 修改 service 后记得 reload
如果修改了:
/etc/systemd/system/myapp.service
需要执行:
sudo systemctl daemon-reload
否则 systemd 可能仍然使用旧配置。
然后根据情况重启:
sudo systemctl restart myapp
常用命令整理
日常基本就是这几个:
systemctl enable myapp systemctl disable myapp systemctl start myapp systemctl stop myapp systemctl restart myapp systemctl status myapp
检查开机启动:
systemctl is-enabled myapp
检查当前运行状态:
systemctl is-active myapp
如果只是记住一点,可以记住:
enable 管开机启动 start 管现在启动
systemctl enable 的本质,就是根据 service 文件里的 [install] 配置创建对应的符号链接,让 systemd 在系统进入指定 target 时自动拉起服务。
到此这篇关于linux服务开机自启动配置指南的文章就介绍到这了,更多相关linux开机自启动配置内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论