Linux 服务开机自启动怎么配置?systemctl enable 原理详解
Linux 服务器上部署 Web 服务、Node.js、Java 程序之后,通常都希望服务器重启后程序能够自动恢复。
使用 systemd 的系统里,最常见的命令就是:
bash
systemctl enable 服务名
很多人会用,但不一定清楚它到底做了什么。
1. 先确认服务是否存在
例如有一个服务:
lua
systemctl status myapp
如果能正常看到服务状态,说明 systemd 已经识别到它。
常见的 service 文件位置有:
perl
/etc/systemd/system/
/usr/lib/systemd/system/
/lib/systemd/system/
自己创建的服务一般放在:
bash
/etc/systemd/system/
比如:
bash
/etc/systemd/system/myapp.service
2. 开启开机自启动
执行:
bash
sudo systemctl enable myapp
正常情况下会看到类似:
perl
Created symlink ...
这一步并不会自动启动当前服务。
如果希望现在就启动,还要执行:
sql
sudo systemctl start myapp
也可以一步完成:
bash
sudo systemctl enable --now myapp
这条命令相当于:
bash
systemctl enable myapp
systemctl start myapp
3. 怎么检查是否已经启用
执行:
csharp
systemctl is-enabled myapp
如果返回:
enabled
说明已经配置开机启动。
如果返回:
scss
disabled
说明没有启用。
查看当前运行状态则是:
csharp
systemctl is-active myapp
这两个状态不要混淆。
一个服务完全可能出现:
scss
enabled
inactive
意思是已经设置开机启动,但现在没有运行。
4. systemctl enable 到底做了什么
systemd 的开机自启动本质上依赖符号链接。
例如 service 文件中有:
ini
[Install]
WantedBy=multi-user.target
执行:
bash
systemctl enable myapp
systemd 会创建类似这样的软链接:
bash
/etc/systemd/system/multi-user.target.wants/myapp.service
指向真正的 service 文件。
可以理解为:
markdown
系统进入 multi-user.target
↓
发现 wants 目录里的 myapp.service
↓
systemd 启动 myapp
所以 enable 本身并不是"启动程序",而是把服务加入对应 target 的启动关系中。
5. 为什么 service 文件需要 Install
一个常见配置:
ini
[Unit]
Description=My Application
After=network.target
[Service]
ExecStart=/usr/bin/node /opt/myapp/app.js
Restart=always
[Install]
WantedBy=multi-user.target
这里:
ini
[Install]
WantedBy=multi-user.target
主要就是给 systemctl enable 使用的。
如果 service 没有 [Install] 部分,执行 enable 时可能会提示:
arduino
The unit files have no installation config
这种服务可能是由其他服务依赖启动的,本身不一定适合直接 enable。
6. 取消开机启动
执行:
bash
sudo systemctl disable myapp
这会删除之前创建的软链接。
但同样需要注意:
bash
systemctl disable myapp
不会自动停止当前正在运行的服务。
如果还想立即停止:
arduino
sudo systemctl stop myapp
或者:
bash
sudo systemctl disable --now myapp
7. 修改 service 后记得 reload
如果修改了:
bash
/etc/systemd/system/myapp.service
需要执行:
sudo systemctl daemon-reload
否则 systemd 可能仍然使用旧配置。
然后根据情况重启:
sudo systemctl restart myapp
常用命令整理
日常基本就是这几个:
bash
systemctl enable myapp
systemctl disable myapp
systemctl start myapp
systemctl stop myapp
systemctl restart myapp
systemctl status myapp
检查开机启动:
csharp
systemctl is-enabled myapp
检查当前运行状态:
csharp
systemctl is-active myapp
如果只是记住一点,可以记住:
bash
enable 管开机启动
start 管现在启动
systemctl enable 的本质,就是根据 service 文件里的 [Install] 配置创建对应的符号链接,让 systemd 在系统进入指定 target 时自动拉起服务。