确认服务单元文件存在于/etc/systemd/system/或/usr/lib/systemd/system/目录下;2. 使用sudo systemctl enable myapp.service命令启用开机自启,systemd会自动创建符号链接至multi-user.target.wants目录;3. 修改服务文件后必须执行sudo systemctl daemon-reload重新加载配置;4. 可通过systemctl is-enabled myapp.service验证自启状态,输出enabled表示设置成功;5. 启用后系统启动时将自动启动该服务,前提是服务文件中[install]段的wantedby=multi-user.target配置正确且服务路径、权限无误,最终确保服务能被systemd正确识别并启动。

在 Linux 系统中,使用
systemd
每个服务都需要一个
.service
/etc/systemd/system/
/usr/lib/systemd/system/
例如,你有一个名为
myapp.service
# /etc/systemd/system/myapp.service [Unit] Description=My Custom Application After=network.target [Service] Type=simple ExecStart=/usr/local/bin/myapp Restart=on-failure User=myuser [Install] WantedBy=multi-user.target
注意:[Install] 段中的 WantedBy= 是设置自启的关键。
使用
systemctl enable
sudo systemctl enable myapp.service
这会创建一个符号链接,将服务文件链接到对应的 target(如
multi-user.target.wants
/etc/systemd/system/multi-user.target.wants/myapp.service → /etc/systemd/system/myapp.service
启用后,系统启动时会自动启动该服务。
# 启用开机自启 sudo systemctl enable myapp.service # 禁用开机自启 sudo systemctl disable myapp.service # 立即启动服务(不重启也生效) sudo systemctl start myapp.service # 查看服务状态 sudo systemctl status myapp.service # 重新加载 systemd 配置(修改服务文件后必须执行) sudo systemctl daemon-reexec sudo systemctl daemon-reload
修改
文件后,务必运行.service登录后复制,否则 systemctl 不会识别变更。daemon-reload登录后复制
[Install]
[Install] WantedBy=multi-user.target
WantedBy=multi-user.target
graphical.target
WantedBy
你也可以使用
RequiredBy
WantedBy
sudo vim /etc/systemd/system/myapp.service
写入内容并保存(参考上面模板)
重新加载 systemd:
sudo systemctl daemon-reload
sudo systemctl enable myapp.service
sudo systemctl start myapp.service
# 查看是否已启用 systemctl is-enabled myapp.service # 输出 enabled 表示成功 # 查看开机启动项列表 systemctl list-unit-files --type=service | grep myapp
基本上就这些。只要服务单元文件正确,并执行
enable
daemon-reload
以上就是如何设置服务自启 systemd服务单元配置的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号