在CentOS上啟動Node.js服務,你需要遵循以下步驟:
確保已經安裝了Node.js。如果還沒有安裝,請訪問Node.js官方網站(https://nodejs.org/)下載并安裝適用于CentOS的Node.js版本。
創建一個Node.js應用程序。在你的項目文件夾中,確保有一個package.json
文件,這個文件包含了項目的元數據和依賴關系。如果沒有這個文件,你需要運行npm init
命令來創建一個。
安裝項目依賴。在項目文件夾中運行npm install
命令,這將根據package.json
文件安裝所有必要的依賴。
創建一個啟動腳本。在你的項目文件夾中創建一個名為start.sh
的文件,然后在文件中添加以下內容:
#!/bin/bash
node app.js
將app.js
替換為你的Node.js應用程序的主入口文件名。
chmod +x start.sh
nodejs.service
的文件,然后在文件中添加以下內容:[Unit]
Description=Node.js Application Service
After=network.target
[Service]
Type=simple
User=<your_user>
WorkingDirectory=<your_project_directory>
ExecStart=/path/to/your/start.sh
Restart=on-failure
[Install]
WantedBy=multi-user.target
將<your_user>
替換為運行Node.js應用程序的用戶,將<your_project_directory>
替換為你的項目文件夾路徑,將/path/to/your/start.sh
替換為你的啟動腳本的實際路徑。
將Systemd服務文件移動到正確的目錄。將nodejs.service
文件移動到/etc/systemd/system/
目錄下。
重新加載Systemd配置。運行以下命令:
sudo systemctl daemon-reload
sudo systemctl start nodejs.service
sudo systemctl enable nodejs.service
現在,你的Node.js服務應該在CentOS上啟動并運行。你可以使用以下命令查看服務狀態:
sudo systemctl status nodejs.service
如果需要停止或重啟服務,可以使用以下命令:
sudo systemctl stop nodejs.service
sudo systemctl restart nodejs.service