> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 systemd 将 Bun 作为守护进程运行

[systemd](https://systemd.io) 是 Linux 的初始化系统和服务管理器。它管理系统进程和服务的启动与控制。

***

要使用 **systemd** 将 Bun 应用作为守护进程运行，请在 `/lib/systemd/system/` 中创建一个\_服务文件\_。

```sh terminal icon="terminal" theme={null}
cd /lib/systemd/system
touch my-app.service
```

***

这是一个典型的服务文件，可在系统启动时运行应用程序。将其作为你自己的服务的模板。将 `YOUR_USER` 替换为运行应用的用户名。要以 `root` 身份运行，将 `YOUR_USER` 替换为 `root`，但出于安全原因不建议这样做。

每个设置的详细信息请参考 [systemd 文档](https://www.freedesktop.org/software/systemd/man/systemd.service.html)。

```ini my-app.service icon="file-code" theme={null}
[Unit]
# 描述应用
Description=My App
# 在网络可用后启动应用
After=network.target

[Service]
# 通常你会使用 'simple'
# 参见 https://www.freedesktop.org/software/systemd/man/systemd.service.html#Type=
Type=simple
# 启动应用时使用的用户
User=YOUR_USER
# 你的应用程序根目录的路径
WorkingDirectory=/home/YOUR_USER/path/to/my-app
# 启动应用的命令
# 需要使用绝对路径
ExecStart=/home/YOUR_USER/.bun/bin/bun run index.ts
# 重启策略
# 可选值：{no|on-success|on-failure|on-abnormal|on-watchdog|on-abort|always}
Restart=always

[Install]
# 自动启动应用
WantedBy=multi-user.target
```

***

如果你的应用程序启动了一个 Web 服务器，非 `root` 用户默认无法监听 80 或 443 端口。要永久允许 Bun 在非 `root` 用户运行时监听这些端口，请使用以下命令。以 `root` 身份运行时不需要此步骤。

```bash terminal icon="terminal" theme={null}
setcap CAP_NET_BIND_SERVICE=+eip ~/.bun/bin/bun
```

***

配置好服务文件后，\_启用\_该服务。启用后，它会在重启时自动启动。这需要 `sudo` 权限。

```bash terminal icon="terminal" theme={null}
systemctl enable my-app
```

***

要在不重启的情况下启动服务，手动\_启动\_它。

```bash terminal icon="terminal" theme={null}
systemctl start my-app
```

***

使用 `systemctl status` 检查应用程序的状态。如果应用成功启动，输出如下所示：

```bash terminal icon="terminal" theme={null}
systemctl status my-app
```

```txt theme={null}
● my-app.service - My App
     已加载：已加载（/lib/systemd/system/my-app.service；已启用；预设：已启用）
     活动：自 Thu 2023-10-12 11:34:08 UTC 起运行中；已运行 1 小时 8 分钟
   主 PID：309641 (bun)
     任务：3（限制：503）
     内存：40.9M
       CPU：1.093s
     CGroup：/system.slice/my-app.service
              └─309641 /home/YOUR_USER/.bun/bin/bun run /home/YOUR_USER/application/index.ts
```

***

要更新服务，编辑服务文件，然后重新加载守护进程。

```bash terminal icon="terminal" theme={null}
systemctl daemon-reload
```

***

有关服务单元配置的完整指南，请参见 [systemd.service 文档](https://www.freedesktop.org/software/systemd/man/systemd.service.html)。或者使用以下常用命令速查表：

```bash terminal icon="terminal" theme={null}
systemctl daemon-reload # 告诉 systemd 某些文件已更改
systemctl enable my-app # 启用应用（允许自动启动）
systemctl disable my-app # 禁用应用（关闭自动启动）
systemctl start my-app # 启动应用（如果已停止）
systemctl stop my-app # 停止应用
systemctl restart my-app # 重启应用
```
