06_Linux中如何让程序重启后自动启动

Linux中如何让程序重启后自动启动

systemd单元文件

Systemd 是现代 Linux 发行版中最常用的初始化系统。你可以通过创建一个 .service 文件来定义服务,并将其放置在 /etc/systemd/system 目录下。

1.创建服务文件

复制代码
sudo touch /etc/systemd/system/myapp.service

在该文件中,可以定义服务的各项属性

复制代码
[Unit]
Description=My Application Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/myapp
Restart=on-failure
User=myuser
WorkingDirectory=/var/lib/myapp

[Install]
WantedBy=multi-user.target

!!!服务配置文件的介绍

假设你的应用程序位于 /opt/myapp 目录下,并且有一个名为 myapp 的可执行文件。我们将创建一个名为 myapp.service 的文件,以定义如何启动、停止和服务的行为。

复制代码
[Unit]
Description=My Application Service
After=network.target

[Service]
Type=simple
User=myuser
Group=mygroup
ExecStart=/opt/myapp/myapp
WorkingDirectory=/opt/myapp
Restart=on-failure
TimeoutSec=30
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=myapp

[Install]
WantedBy=multi-user.target

Unit\] 部分 Description:服务的描述。 After:定义此服务依赖于哪些其他服务。在这里,我们指定 network.target,意味着服务将在网络准备好之后启动。 \[Service\] 部分 Type:定义服务的启动类型。simple 表示服务只需启动一个主进程。 User:指定服务运行时使用的用户。 Group:指定服务运行时使用的组。 ExecStart:指定启动服务时应执行的命令。这里是启动 /opt/myapp/myapp。 WorkingDirectory:指定服务的工作目录。 Restart:定义服务在失败后的重启策略。on-failure 表示只有在服务异常退出时才重启。 TimeoutSec:定义服务启动的最大超时时间,单位为秒。 StandardOutput 和 StandardError:指定标准输出和标准错误输出的位置。这里设置为 syslog,表示输出将被发送到系统日志。 SyslogIdentifier:定义发送到 syslog 的消息的标识符。 \[Install\] 部分 WantedBy:指定此服务应该在哪个目标中激活。multi-user.target 表示服务应在多用户模式下启动。

2.需要配置服务的状态(加载和启用服务)

复制代码
sudo systemctl daemon-reload //重新加载服务
sudo systemctl enable myapp.service
sudo systemctl start myapp.service

3.验证服务程序的运行状态

复制代码
sudo systemctl status myapp.service

4.打印程序的标准输出

复制代码
journalctl -f
相关推荐
可爱又迷人的反派角色“yang”32 分钟前
ansible剧本编写(三)
linux·网络·云计算·ansible
m0_7381207237 分钟前
应急响应——知攻善防Web-3靶机详细教程
服务器·前端·网络·安全·web安全·php
石像鬼₧魂石6 小时前
内网渗透靶场实操清单(基于 Vulhub+Metasploitable 2)
linux·windows·学习·ubuntu
Danileaf_Guo6 小时前
256台H100服务器算力中心的带外管理网络建设方案
运维·服务器
橘子真甜~7 小时前
C/C++ Linux网络编程15 - 网络层IP协议
linux·网络·c++·网络协议·tcp/ip·计算机网络·网络层
拾贰_C8 小时前
【Linux | Windows | Terminal Command】 Linux---grep | Windows--- findstr
linux·运维·服务器
阿华hhh9 小时前
Linux系统编程(标准io)
linux·开发语言·c++
石像鬼₧魂石9 小时前
Kali Linux 网络端口深度扫描
linux·运维·网络
alengan9 小时前
linux上面写python3日志服务器
linux·运维·服务器
Rose sait10 小时前
【环境配置】Linux配置虚拟环境pytorch
linux·人工智能·python