Ubuntu 配置服务后台运行

2025-11-15

经常在工作中会把一些常用的功能,做成服务,供内网公共使用,极大的提高使用效率。

下面记录了在 Ubuntu 上配置服务后台运行的标准流程,可以拿来即用。

1、创建systemd服务文件

sudo vi /etc/systemd/system/myservice.service

把其中的 myservice 改为自己的服务名。

2、编辑文件内容

这是关键的一步,配置内容就是我们服务的启动参数信息。

[Unit]
Description=My Custom Service
After=network.target

[Service]
Type=simple
User=yourusername
WorkingDirectory=/path/to/your/app
ExecStart=/usr/bin/python3 /path/to/your/app/main.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

[Unit] 段 – 服务描述与依赖关系

[Service] 段 – 服务运行行为

[Install] 段 – 服务安装配置

3、管理服务常用命令

# 重新加载systemd配置
sudo systemctl daemon-reload

# 启动服务
sudo systemctl start myservice

# 设置开机自启
sudo systemctl enable myservice

# 查看服务状态
sudo systemctl status myservice

# 停止服务
sudo systemctl stop myservice

# 查看日志
sudo journalctl -u myservice -f

正常情况下,按上面配置文件配置后启动服务,status 查看服务状态是 active (running) 就没什么问题,如果有问题,也会提示具体的错误,发给 AI 定位排查一下即可。

以上,希望能给你的 AI 提供一份正确的养料。

#测试运维 3

1
收藏
已读
分享
X