.service
文件是 linux 系统中 systemd
服务管理器的配置文件,用于定义如何启动、管理和监控系统服务(如后台程序、守护进程等)。以下是它的核心作用和详细使用指南:
一、.service 文件的核心作用
1.定义服务行为
描述服务的启动命令、依赖关系、重启策略、运行环境等。
2.服务生命周期管理
通过 systemctl
命令启动、停止、重启服务,或设置开机自启。
3.统一管理标准
标准化服务的配置方式,简化运维操作。
二、.service 文件的核心结构
一个典型的 .service
文件分为三个部分(以 [unit]
、[service]
、[install]
为块):
1.[unit]块
定义服务的元信息和依赖关系。
[unit] description=服务描述 after=依赖的目标或服务(如 network.target) requires=强依赖的其他服务 wants=弱依赖的其他服务
2.[service]块
定义服务运行的具体行为。
[service] type=服务类型(simple, forking, oneshot 等) execstart=启动命令 restart=重启策略(no, on-failure, always) user=运行服务的用户 group=运行服务的用户组 environment=环境变量(如 path=/usr/bin) workingdirectory=工作目录
3.[install]块
定义如何将服务安装到系统启动目标。
[install] wantedby=multi-user.target # 关联到多用户命令行模式
三、如何使用 .service 文件
场景示例:部署一个自定义服务(如chogori-agent)
假设你有一个程序 /opt/chogori/bin/chogori-agent
,需要将其配置为系统服务。
1. 创建 .service 文件
在 /etc/systemd/system/
目录下创建文件 chogori-agent.service
:
sudo nano /etc/systemd/system/chogori-agent.service
2. 编写服务配置
[unit] description=chogori agent service after=network.target [service] type=simple execstart=/opt/chogori/bin/chogori-agent \ --config /opt/chogori/etc/agent.yaml \ --log /var/log/chogori/agent.log restart=on-failure user=chogori group=chogori environment="path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin" [install] wantedby=multi-user.target
3. 设置权限和路径
确保程序和配置文件可访问:
sudo mkdir -p /var/log/chogori sudo chown -r chogori:chogori /opt/chogori /var/log/chogori
4. 重载 systemd 配置
sudo systemctl daemon-reload
5. 操作服务
启动服务:
sudo systemctl start chogori-agent
设置开机自启:
sudo systemctl enable chogori-agent
查看状态:
systemctl status chogori-agent
停止服务:
sudo systemctl stop chogori-agent
查看日志:
journalctl -u chogori-agent -f
四、关键参数详解
1.[service]块核心参数
参数 | 作用 |
---|---|
type=simple | 默认类型,直接运行 execstart 命令(前台运行)。 |
type=forking | 适用于后台守护进程(需自行 fork)。 |
restart=on-failure | 服务异常退出时自动重启(其他值:no, always, on-abnormal)。 |
user 和 group | 指定运行服务的用户和组(提升安全性)。 |
2. 环境变量设置
单变量:
environment="key=value"
多变量:
environment="key1=value1" "key2=value2"
五、常见问题排查
1. 服务启动失败
# 查看详细日志 journalctl -u chogori-agent -b --no-pager
常见原因:
execstart
路径错误。- 权限不足(用户/组或文件权限)。
- 依赖服务未启动(如
after=postgresql.service
但 postgresql 未运行)。
2. 服务无法开机自启
# 检查服务是否已启用 systemctl is-enabled chogori-agent
修复:
sudo systemctl enable chogori-agent
六、总结
.service
文件本质:是systemd
的配置文件,用于定义服务的启动和管理规则。- 核心操作:创建文件 → 编写配置 → 重载配置 → 启动/管理服务。
- 最佳实践:始终通过
systemctl
管理服务,而非直接运行程序。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论