阅读量:0
在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项目的基本流程,具体项目可能需要根据项目代码和需求进行相应的调整。
以上就是关于“ubuntu上nodejs项目如何部署”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm