在Ubuntu上部署Node.js项目通常涉及以下几个步骤:
sudo apt update
sudo apt upgrade
sudo apt install -y build-essential libssl-dev
sudo apt install nodejs npm
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt install nodejs
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
source ~/.bashrc
nvm install node
node -v
npm -v
mkdir my-node-app
cd my-node-app
npm init -y
touch server.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
npm install express --save
node server.js
sudo apt install nginx
/etc/nginx/sites-available/default 文件,添加以下内容:server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1: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;
}
}
sudo systemctl restart nginx
sudo npm install -g pm2
pm2 start server.js
通过以上步骤,你可以在Ubuntu上成功部署Node.js项目。根据你的需求选择合适的安装方法,并使用Nginx作为反向代理来处理生产环境中的请求。