在Ubuntu上部署Node.js项目可以通过以下步骤完成:
安装Node.js和npm
- 使用NodeSource安装Node.js:
curl -sL https://deb.nodesource.com/setup_16.x | sudo bash - sudo apt-get install -y nodejs
或者安装最新LTS版本的Node.js:
curl -sL https://deb.nodesource.com/setup_20.x | sudo bash - sudo apt-get install -y nodejs
- 验证安装:
node -v npm -v
创建和配置Node.js项目
- 创建项目目录:
mkdir my-node-app cd my-node-app
- 初始化项目:
npm init -y
- 安装项目依赖:
npm install express --save
- 创建服务器文件(例如
app.js
):
const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
启动Node.js应用
- 使用npm启动应用:
npm start
或者使用forever
使应用在后台运行:
npm install -g forever forever start app.js
使用Nginx作为反向代理(可选)
- 安装Nginx:
sudo apt-get install nginx
- 配置Nginx:
编辑/etc/nginx/sites-available/default
文件,添加以下内容:
server { listen 80; server_name example.com; location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }
- 重启Nginx:
sudo systemctl restart nginx
使用PM2管理Node.js进程(可选)
- 安装PM2:
sudo npm install -g pm2
- 使用PM2启动应用:
pm2 start app.js
- 设置PM2开机自启动:
pm2 startup
以上步骤是在Ubuntu上部署Node.js项目的基本流程,具体项目可能需要根据项目代码和需求进行相应的调整。