创建 Systemd 服务文件
在 /etc/systemd/system/
目录下创建一个新的服务文件,例如 my_service.service
。使用文本编辑器打开并编辑该文件:
sudo nano /etc/systemd/system/my_service.service
在文件中添加以下内容:
[Unit]
Description=My Custom Service
After=network.target
[Service]
Type=simple
ExecStart=/path/to/your/executable
Restart=always
User=your_username
WorkingDirectory=/path/to/working/directory
[Install]
WantedBy=multi-user.target
解释服务文件内容
- Description:服务的描述信息。
- After:指定服务在哪些目标之后启动,通常设置为
network.target
以等待网络就绪。 - Type:服务类型,
simple
表示直接运行程序。 - ExecStart:程序的完整路径。
- Restart:设置为
always
表示程序崩溃后自动重启。 - User:运行该服务的用户。
- WorkingDirectory:程序的工作目录。
重新加载 Systemd 配置
保存文件后,运行以下命令重新加载 Systemd 配置:
sudo systemctl daemon-reload
启动服务
使用以下命令启动服务:
sudo systemctl start my_service
检查服务状态
验证服务是否正常运行:
sudo systemctl status my_service
设置开机自启
启用服务以在系统启动时自动运行:
sudo systemctl enable my_service
验证开机自启
重启系统后,检查服务是否自动启动:
sudo systemctl status my_service
停止或禁用服务
如果需要停止服务:
sudo systemctl stop my_service
禁用开机自启:
sudo systemctl disable my_service
日志查看
服务日志可通过 journalctl
查看:
sudo journalctl -u my_service -f
注意事项
- 确保程序路径和权限正确。
- 使用绝对路径避免依赖环境变量问题。
- 测试服务确保无依赖缺失或配置错误。