在 CentOS 系统中,启动和停止 Node.js 服务通常需要使用命令行。以下是一些基本步骤,用于启动和停止 Node.js 服务:
首先,确保已经安装了 Node.js。如果尚未安装,请访问 Node.js 官网 下载并安装适用于 CentOS 的版本。
创建一个简单的 Node.js 应用程序。例如,创建一个名为 app.js 的文件,其中包含以下内容:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
npm 或 yarn 安装项目依赖项。在项目目录中运行以下命令之一:npm install
或
yarn install
systemd 的文件夹,并在其中创建一个名为 nodejs.service 的文件。将以下内容粘贴到该文件中:[Unit]
Description=Node.js Application Service
After=syslog.target network.target
[Service]
Type=simple
User=<your_user>
WorkingDirectory=/path/to/your/nodejs/app
ExecStart=/usr/bin/node /path/to/your/nodejs/app/app.js
Restart=on-failure
[Install]
WantedBy=multi-user.target
请将 <your_user> 替换为您的用户名,将 /path/to/your/nodejs/app 替换为您的 Node.js 应用程序的路径。
nodejs.service 文件移动到 /etc/systemd/system/ 目录:sudo mv nodejs.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl start nodejs.service
sudo systemctl status nodejs.service
sudo systemctl stop nodejs.service
sudo systemctl enable nodejs.service
现在,您已经知道如何在 CentOS 系统中启动和停止 Node.js 服务。