Linux下项目开机自启服务

在 Ubuntu(所有现代版本,16.04+)下,让可执行文件开机自启,最稳定、最推荐的方法是配置 systemd 服务

一、后台程序 / 服务:systemd 服务

1. 创建服务文件

复制代码
sudo nano /etc/systemd/system/你的服务名.service

2. 写入模板

bash 复制代码
# ===================== [Unit] 区块:服务整体说明、启动依赖 =====================
[Unit]
# Description:纯备注,给人/系统看的,说明这个服务是干啥的,随便改,不影响运行
Description=我的服务器

# After=network.target:意思是【等系统网络完全启动好了,再启动这个服务】
# 你的服务如果要对外提供接口、联网、监听端口,必须加这行;没网就启动会报错
After=network.target

# ===================== [Service] 区块:真正控制程序怎么跑 =====================
[Service]
# Type=simple:最常用模式,代表 ExecStart 里的程序是【主进程】,前台跑、常驻后台
# 大多数自研程序、接口服务、二进制可执行文件,都用这个
Type=simple

# ExecStart:重中之重!!程序启动的【绝对完整路径】
# 系统会按这个路径去找你的项目可执行文件或脚本,错一个字母、路径不对直接启动失败
ExecStart=/home/ubuntu24/PPOCR/mycode

# User=root:用 root 管理员身份运行这个程序
# 好处:有权限监听端口、读写任意文件夹、不会权限不足报错
# 注意:非必要不推荐,但本地内网服务没问题
User=root

# Restart=on-failure:程序崩了、闪退、报错退出,系统自动帮你重启
# 只在程序异常挂掉时重启;你手动stop,不会乱重启
Restart=on-failure

# RestartSec=3:程序挂掉后,等待3秒,再自动重启
RestartSec=3

# ===================== [Install] 区块:控制开机自启 =====================
[Install]
# WantedBy=multi-user.target:代表开机进入正常桌面/命令行多用户模式时,启动这个服务
# 标准通用配置,所有后台服务(ollama/接口/脚本)都写这个就行,不用改
WantedBy=multi-user.target

3. 生效 & 开机自启

bash 复制代码
# 重载 systemd
sudo systemctl daemon-reload

# 启用开机自启
sudo systemctl enable 你的服务名

# 立即启动(测试)
sudo systemctl start 你的服务名

# 查看状态
sudo systemctl status 你的服务名

4. 常用命令

bash 复制代码
#重载配置(改文件后必用)
sudo systemctl daemon-reload

#开机自启
sudo systemctl enable 我的服务

#取消开机自启
sudo systemctl disable 我的服务

#启动
sudo systemctl start 我的服务

#停止
sudo systemctl stop 我的服务

#重启
sudo systemctl restart 我的服务

#看运行状态
sudo systemctl status 我的服务

#实时看日志排错
journalctl -u 我的服务-f

二、日志输出成日志文件

1. 创建脚本

start.sh

bash 复制代码
#!/bin/bash

# 生成时间戳 年月日_时分秒,日志保存的路径
TS=$(date +%Y%m%d_%H%M%S)
LOG_DIR=/home/ubuntu24/server_log

# 正常日志+错误日志分开
exec >> ${LOG_DIR}/ocr_${TS}.log 2>> ${LOG_DIR}/ocr_err_${TS}.log

# 执行你的主程序
/home/ubuntu24/mycode

2. 路径替换

将自启动 服务.serviceExecStart下路径换成 脚本start.sh

再执行:

bash 复制代码
#重载配置(改文件后必用)
sudo systemctl daemon-reload

#重启
sudo systemctl restart 我的服务

#看运行状态
sudo systemctl status 我的服务
相关推荐
@insist1232 小时前
网络工程师-因特网与网络互联(二):ARP 与 ICMP,网络层排错双雄
服务器·网络·网络协议·网络工程师·软考·软件水平考试
charlie1145141912 小时前
嵌入式Linux驱动开发——模块参数与内核调试:让模块“活“起来的魔法
linux·驱动开发·学习·c
陳10302 小时前
Linux:入门开发工具--Git和GUN调试器
linux·运维·git
DeepHacking2 小时前
Ubuntu 上安装 ComfyUI(NVIDIA GPU / Conda / CUDA 12.1)
linux·ubuntu·conda
IT界的老黄牛2 小时前
后端 2ms,页面 7 秒:一次 CDN“帮倒忙“的排查实录
运维·网络
YQ_012 小时前
Ubuntu 执行 `ubuntu-drivers autoinstall` 后,Wi‑Fi 消失、外接显示器无反应的排查与修复
linux·运维·ubuntu
m0_738120722 小时前
渗透基础知识ctfshow——Web应用安全与防护(第二章)
服务器·前端·安全·web安全·php
绵羊20232 小时前
CRISPAR-Cas9技术原理
linux
李李李li2 小时前
ubuntu22.04mt76x2u网卡断网
linux·运维·服务器