在CentOS上部署Node.js项目可以按照以下步骤进行:
-
更新系统: 首先,确保你的系统是最新的。
sudo yum update -y
-
安装Node.js: 使用NodeSource仓库安装最新版本的Node.js。
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash - sudo yum install -y nodejs
-
安装Nginx(反向代理): 安装Nginx以便实现反向代理。
sudo yum install -y nginx
-
创建项目目录: 创建一个新的项目目录并进入该目录。
mkdir myapp cd myapp
-
初始化项目: 初始化一个新的Node.js项目。
npm init -y
-
安装Express和EJS: 安装Express框架和EJS模板引擎。
npm install express ejs
-
创建服务器文件: 创建一个
app.js
文件并写入以下内容:const express = require('express'); const app = express(); app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('index', { title: '首页' }); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
-
创建EJS模板: 在项目根目录下创建
views
文件夹,并在其中创建index.ejs
文件。 -
配置Nginx反向代理: 编辑Nginx配置文件
/etc/nginx/nginx.conf
,在http块中添加以下配置:server { listen 80; server_name yourdomain.com; location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
-
重启Nginx: 重启Nginx以应用更改。
sudo systemctl restart nginx
-
启动项目: 在终端中运行以下命令启动你的Node.js应用。
node app.js
通过以上步骤,你已成功在CentOS上部署了Node.js项目,并通过Nginx实现了反向代理。