溫馨提示×

ubuntu上nodejs項目如何部署

小樊
58
2025-03-06 03:26:10
欄目: 編程語言

在Ubuntu上部署Node.js項目可以通過以下步驟完成:

安裝Node.js和npm

  1. 使用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
  1. 驗證安裝
node -v
npm -v

創建和配置Node.js項目

  1. 創建項目目錄
mkdir my-node-app
cd my-node-app
  1. 初始化項目
npm init -y
  1. 安裝項目依賴
npm install express --save
  1. 創建服務器文件(例如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應用

  1. 使用npm啟動應用
npm start

或者使用forever使應用在后臺運行:

npm install -g forever
forever start app.js

使用Nginx作為反向代理(可選)

  1. 安裝Nginx
sudo apt-get install nginx
  1. 配置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;
  }
}
  1. 重啟Nginx
sudo systemctl restart nginx

使用PM2管理Node.js進程(可選)

  1. 安裝PM2
sudo npm install -g pm2
  1. 使用PM2啟動應用
pm2 start app.js
  1. 設置PM2開機自啟動
pm2 startup

以上步驟是在Ubuntu上部署Node.js項目的基本流程,具體項目可能需要根據項目代碼和需求進行相應的調整。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女