Bun

指南生态系统

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

systemd 是 Linux 操作系统的 init 系统和服务的管理器,负责管理系统进程和服务的启动和控制。

要将 Bun 应用程序以守护进程方式运行,使用 systemd,您需要在 /lib/systemd/system/ 目录下创建一个服务文件

cd /lib/systemd/system
touch my-app.service

这是一个典型的服务文件,用于在系统启动时运行应用程序。您可以将其作为模板用于您自己的服务。将 YOUR_USER 替换为您希望运行应用程序的用户名称。要以 root 用户身份运行,请将 YOUR_USER 替换为 root,尽管出于安全原因,通常不建议这样做。

有关每个设置的更多信息,请参阅 systemd 文档

my-app.service
[Unit]
# describe the app
Description=My App
# start the app after the network is available
After=network.target

[Service]
# usually you'll use 'simple'
# one of https://www.freedesktop.org/software/systemd/man/systemd.service.html#Type=
Type=simple
# which user to use when starting the app
User=YOUR_USER
# path to your application's root directory
WorkingDirectory=/home/YOUR_USER/path/to/my-app
# the command to start the app
# requires absolute paths
ExecStart=/home/YOUR_USER/.bun/bin/bun run index.ts
# restart policy
# one of {no|on-success|on-failure|on-abnormal|on-watchdog|on-abort|always}
Restart=always

[Install]
# start the app automatically
WantedBy=multi-user.target

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

sudo setcap CAP_NET_BIND_SERVICE=+eip ~/.bun/bin/bun

配置好服务文件后,您现在可以启用该服务。启用后,它将在重启时自动启动。这需要 sudo 权限。

sudo systemctl enable my-app

要启动服务而不重启,您可以手动启动它。

sudo systemctl start my-app

使用 systemctl status 检查您的应用程序的状态。如果您的应用程序已成功启动,您应该会看到类似以下内容

sudo systemctl status my-app
● my-app.service - My App
     Loaded: loaded (/lib/systemd/system/my-app.service; enabled; preset: enabled)
     Active: active (running) since Thu 2023-10-12 11:34:08 UTC; 1h 8min ago
   Main PID: 309641 (bun)
      Tasks: 3 (limit: 503)
     Memory: 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

要更新服务,请编辑服务文件的内容,然后重新加载守护进程。

sudo systemctl daemon-reload

有关服务单元配置的完整指南,您可以查看 此页面。或者参考此常用命令备忘单

sudo systemctl daemon-reload # tell systemd that some files got changed
sudo systemctl enable my-app # enable the app (to allow auto-start)
sudo systemctl disable my-app # disable the app (turns off auto-start)
sudo systemctl start my-app # start the app if is stopped
sudo systemctl stop my-app # stop the app
sudo systemctl restart my-app # restart the app