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 表示持续输出最新的日志
相关推荐
orion5713 小时前
Missing Semester Class1:course overview and introduction of shell
linux
SkyWalking中文站17 小时前
认识 Horizon UI · 6/17:Trace 探索器
运维·监控·自动化运维
用户1204872216119 小时前
Linux驱动编译与加载
linux·嵌入式
火车叼位21 小时前
写给初级开发者:SSL、SSH、HTTPS 与证书体系全解析
运维
用户805533698031 天前
Input 子系统架构:Core、Handler、Driver 三层是怎么协作的
linux·嵌入式
用户805533698031 天前
RK-Forge外设系列开篇 - 把板子从「能启动」变成「能用」:Ethernet/SPI/MMC 三个纯接线外设
linux·github·嵌入式
小猿姐1 天前
唯品会大规模数据库云原生实践:基于 KubeBlocks 管理数千实例的统一运维之路
运维·elasticsearch·云原生
七歌杜金房2 天前
我终于又有了自己的 Linux 电脑
linux·debian·mac
SkyWalking中文站2 天前
认识 Horizon UI · 5/17:3D 基础设施地图
运维·监控·自动化运维
tntxia3 天前
linux curl命令详解_curl详解
linux