阅读量:1
在 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=
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
请将 替换为您的用户名,将 /path/to/your/nodejs/app 替换为您的 Node.js 应用程序的路径。
- 将
nodejs.service文件移动到/etc/systemd/system/目录:
sudo mv nodejs.service /etc/systemd/system/
- 重新加载 systemd 配置:
sudo systemctl daemon-reload
- 启动 Node.js 服务:
sudo systemctl start nodejs.service
- 检查服务状态:
sudo systemctl status nodejs.service
- 停止 Node.js 服务:
sudo systemctl stop nodejs.service
- 若要在系统启动时自动运行此服务,请执行以下命令:
sudo systemctl enable nodejs.service
现在,您已经知道如何在 CentOS 系统中启动和停止 Node.js 服务。
以上就是关于“CentOS Node.js服务如何启动与停止”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm