当前位置: 代码网 > 服务器>服务器>Linux > Linux创建服务使用systemctl管理详解

Linux创建服务使用systemctl管理详解

2025年09月29日 Linux 我要评论
创建服务 /usr/lib/systemd/system/[unit]# 服务描述(自定义,便于识别)description=sftp directory sync service (inotifyw

创建服务 /usr/lib/systemd/system/

[unit]
# 服务描述(自定义,便于识别)
description=sftp directory sync service (inotifywait + rsync daemon)
# 服务依赖:网络启动后、rsync 服务启动后再启动本服务(确保网络和依赖可用)
after=network.target rsyncd.service
# 服务文档(可选,指向命令手册)
documentation=man:inotifywait(1) man:rsync(1)

[service]
# 服务类型:simple(前台运行,适合持续监控的脚本)
type=simple
# 执行服务的用户/组(建议用 root,避免目录、密码文件权限不足)
user=root
group=root
# 工作目录(脚本所在目录,避免相对路径问题)
workingdirectory=/usr/local/bin/sftp_sync
# 核心:服务启动命令(脚本绝对路径,必须正确)
execstart=/usr/local/bin/sftp_sync/sftp_sync_daemon.sh
# 服务意外退出时自动重启(确保稳定性,如脚本崩溃后恢复)
restart=always
# 重启间隔(意外退出后,5秒再重启,避免频繁重启)
restartsec=5
# 停止服务时,杀死所有子进程(避免 inotifywait 残留)
killmode=control-group
# 输出重定向到 journalctl(可通过 journalctl 查看服务运行日志)
standardoutput=journal
standarderror=journal

[install]
# 服务安装目标:多用户模式下开机自启(适配服务器环境)
wantedby=multi-user.target

设置服务文件权限:所有者读写,其他用户只读

chmod 644 /usr/lib/systemd/system/sftp-sync-daemon.service

systemctl 配置

  1. 重新加载 systemd 配置
systemctl daemon-reload
  1. 启动服务
systemctl start sftp-sync-daemon
  1. 查看服务状态(关键!确认是否正常运行)
systemctl status sftp-sync-daemon -l

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com