ubuntu 创建系统服务 开机自启

现在有一个可执行文件如 iotserver 需要长期运行,并且开机自启动远行

一 步骤

1 确保 iotserver 可执行文件具有执行权限

bash 复制代码
chmod +x /home/tg/iot/iotserver 

2 单独运行确认可以运行

/home/tg/iot/iotserver

3 创建服务文件

bash 复制代码
sudo nano /etc/systemd/system/iotserver.service

文件内容如下

bash 复制代码
[Unit]
# 服务的描述,说明这是IOT服务器
Description=IotServer Server 
# 指定在网络服务启动后再启动此服务,确保网络可用:cite[4]:cite[10]
After=network.target  

[Service]
 # 服务类型,一般为simple或forking,如果你的进程会后台化(daemonize),可能需要用forking
Type=simple    
 # 指定运行此服务的用户,出于安全考虑,建议在测试成功后改用非root用户(如:www-data, nobody或新建专用用户)     
User=root   
# 指定运行此服务的用户组        
Group=root    
 # 定义进程退出后的重启方式,always表示总是重启:cite[4]       
Restart=always   
 # 重启服务之前需要等待的秒数:cite[4]   
RestartSec=5     
# 替换为iotserver程序所在的工作目录的绝对路径,这很重要,因为它决定了程序的当前目录   
WorkingDirectory=/home/tg/iot 
# 替换为iotserver可执行文件的绝对路径
ExecStart=/home/tg/iot/iotserver 
# 如果不需要丢弃输出,可以移除 StandardOutput 和 StandardError 配置,日志将由 systemd 的 journal 管理
# 将标准输出重定向到空设备,类似 >/dev/null
# StandardOutput=null 
# 将标准错误重定向到空设备,类似 2>/dev/null
# StandardError=null  
# 或者,如果你想将日志输出到特定文件,可以使用:
# StandardOutput=file:/var/log/iotserver.log
# StandardError=file:/var/log/iotserver.error.log

[Install]
# 指定服务在多用户模式下启用,这是常规的多用户命令行界面运行级别:cite[4]:cite[10]
WantedBy=multi-user.target 

4 重新加载systemd配置

bash 复制代码
sudo systemctl daemon-reload

5 启动服务,并设置它开机自启:

bash 复制代码
sudo systemctl start iotserver    # 启动服务
sudo systemctl enable iotserver   # 启用开机自启

6 使用以下命令检查服务是否正常运行28:

bash 复制代码
sudo systemctl status iotserver

如果服务运行失败,这个命令通常会显示简短的错误信息。

7 要查看更详细的日志,可以使用:

bash 复制代码
journalctl -u iotserver.service -f  # -f 表示持续输出最新的日志
相关推荐
Johny_Zhao11 小时前
OpenClaw安装部署教程
linux·人工智能·ai·云计算·系统运维·openclaw
chlk1232 天前
Linux文件权限完全图解:读懂 ls -l 和 chmod 755 背后的秘密
linux·操作系统
舒一笑2 天前
Ubuntu系统安装CodeX出现问题
linux·后端
改一下配置文件2 天前
Ubuntu24.04安装NVIDIA驱动完整指南(含Secure Boot解决方案)
linux
碳基沙盒2 天前
OpenClaw 多 Agent 配置实战指南
运维
深紫色的三北六号2 天前
Linux 服务器磁盘扩容与目录迁移:rsync + bind mount 实现服务无感迁移(无需修改配置)
linux·扩容·服务迁移
SudosuBash3 天前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
哈基咪怎么可能是AI3 天前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github
十日十行4 天前
Linux和window共享文件夹
linux
木心月转码ing4 天前
WSL+Cpp开发环境配置
linux