使用 systemd 管理 Linux 服务:配置与自动重启指南
使用 systemd (推荐,适用于大多数 Linux 发行版)
systemd 是现代 Linux 系统中最常用的服务管理器。它能可靠地管理进程,并在进程崩溃时自动重启。
创建 systemd 服务文件:
创建一个文件,例如 /etc/systemd/system/app.service,并用以下内容填充它(你需要根据你的实际路径和用户调整):
vi /etc/systemd/system/app.service
[Unit]
Description=app Service
After=network.target[Service]
User=your_user
MemoryLimit=200M
WorkingDirectory=/path/to/app
ExecStart=/path/to/app/app -d .
Restart=on-failure
RestartSec=5
StandardOutput=append:/path/to/app/app_2025.log
StandardError=append:/path/to/app/app_2025.log[Install]
WantedBy=multi-user.target
注意:文件内容中不要含有注释,否则会出现:
Description: 服务的描述。
After: 定义服务启动的依赖关系,这里表示在网络启动后启动。
User: 运行 app 进程的用户。非常重要,替换成你的用户名。 如果不指定,默认是 root,可能导致权限问题。
WorkingDirectory: app 的工作目录,这很重要,因为 -d . 是相对于这个目录的。
ExecStart: 实际执行的命令。 替换成 app 可执行文件的完整路径。
Restart=on-failure: 当进程异常退出时,自动重启。
RestartSec: 重启前的等待时间,防止频繁重启。
StandardOutput 和 StandardError: 指定标准输出和标准错误输出的日志文件。 使用 append 意味着追加到日志文件,而不是覆盖。替换为你希望的路径
WantedBy: 定义服务在哪个 target 下启动。multi-user.target 适合于大多数情况,表示多用户环境。
启用并启动服务:
sudo systemctl daemon-reload # 重新加载 systemd 配置
sudo systemctl enable app # 设置开机自启
sudo systemctl start app # 立即启动服务
sudo systemctl status app # 检查服务状态
daemon-reload: 每次修改 .service 文件后都需要运行此命令,以使 systemd 重新加载配置。
enable: 设置开机自启动。
start: 立即启动服务。
status: 查看服务的状态,包括是否正在运行、日志输出等。
查看日志:
可以使用 journalctl -u app 命令查看 app 服务的日志。 或者直接查看你在 .service 文件中指定的日志文件。