温馨提示×

CentOS Node.js服务如何启动与停止

小樊
48
2025-10-04 22:17:05
栏目: 编程语言

在 CentOS 系统中,启动和停止 Node.js 服务通常需要使用命令行。以下是一些基本步骤,用于启动和停止 Node.js 服务:

  1. 首先,确保已经安装了 Node.js。如果尚未安装,请访问 Node.js 官网 下载并安装适用于 CentOS 的版本。

  2. 创建一个简单的 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}/`);
});
  1. 使用 npmyarn 安装项目依赖项。在项目目录中运行以下命令之一:
npm install

yarn install
  1. 在项目目录中创建一个名为 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 应用程序的路径。

  1. nodejs.service 文件移动到 /etc/systemd/system/ 目录:
sudo mv nodejs.service /etc/systemd/system/
  1. 重新加载 systemd 配置:
sudo systemctl daemon-reload
  1. 启动 Node.js 服务:
sudo systemctl start nodejs.service
  1. 检查服务状态:
sudo systemctl status nodejs.service
  1. 停止 Node.js 服务:
sudo systemctl stop nodejs.service
  1. 若要在系统启动时自动运行此服务,请执行以下命令:
sudo systemctl enable nodejs.service

现在,您已经知道如何在 CentOS 系统中启动和停止 Node.js 服务。

0