温馨提示×

ubuntu下js项目如何部署

小樊
47
2025-08-15 19:58:22
栏目: 编程语言

在Ubuntu下部署JS项目(以Node.js项目为例)的核心步骤如下:

1. 系统初始化与环境准备

  • 更新系统sudo apt update && sudo apt upgrade -y
  • 安装基础工具sudo apt install -y build-essential git curl
  • 安装Node.js
    • 推荐使用NodeSource PPA安装LTS版本:
      curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
      sudo apt install -y nodejs
    • 验证安装:node -vnpm -v

2. 项目部署

  • 上传项目
    • 通过SCP/SFTP:scp -r /本地项目路径 ubuntu@服务器IP:/目标路径
    • 或通过Git克隆:git clone https://仓库地址.git
  • 安装依赖:进入项目目录执行 npm install
  • 配置环境变量:在项目根目录创建.env文件,定义如PORT=3000等变量

3. 启动应用

  • 直接启动(开发环境)node app.js(需在package.json中配置"start": "node app.js"
  • 生产环境推荐(PM2管理)
    • 安装PM2:sudo npm install -g pm2
    • 启动应用:pm2 start app.js --name "项目名"
    • 设置开机自启:pm2 startup systemd 并按提示执行命令

4. 配置Nginx反向代理(可选,生产环境必备)

  • 安装Nginx:sudo apt install nginx
  • 编辑配置文件(如/etc/nginx/sites-available/your-domain.conf):
    server {  
      listen 80;  
      server_name your-domain.com;  
      location / {  
        proxy_pass http://localhost:3000;  # 转发到Node.js端口  
        proxy_set_header Host $host;  
      }  
    }  
    
  • 启用配置并重启Nginx:
    sudo ln -s /etc/nginx/sites-available/your-domain.conf /etc/nginx/sites-enabled/
    sudo nginx -t && sudo systemctl restart nginx

5. 安全与优化

  • 开放防火墙sudo ufw allow 'Nginx Full'
  • 配置SSL证书(可选):使用Let’s Encrypt免费证书:
    sudo apt install certbot python3-certbot-nginx
    sudo certbot --nginx -d your-domain.com

6. 常用维护命令

  • 查看应用状态:pm2 list
  • 重启应用:pm2 restart 项目名
  • 查看日志:pm2 logs

说明:若项目为前端静态文件,可直接通过Nginx托管(无需Node.js运行时),步骤简化为上传文件+配置Nginx静态资源路径。

参考来源:

0