systemd 是 Linux 作業系統的 init 系統和服務的管理器,負責管理系統程序和服務的啟動和控制。
要將 Bun 應用程式以守護程序方式執行,使用 systemd,您需要在 /lib/systemd/system/ 目錄下建立一個服務檔案。
cd /lib/systemd/systemtouch my-app.service這是一個典型的服務檔案,用於在系統啟動時執行應用程式。您可以將其作為模板用於您自己的服務。將 YOUR_USER 替換為您希望執行應用程式的使用者名稱稱。要以 root 使用者身份執行,請將 YOUR_USER 替換為 root,儘管出於安全原因,通常不建議這樣做。
有關每個設定的更多資訊,請參閱 systemd 文件。
[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 changedsudo 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 stoppedsudo systemctl stop my-app # stop the appsudo systemctl restart my-app # restart the app