ubuntu

ubuntu中js项目如何部署上线

小樊
44
2025-08-27 21:57:41
栏目: 编程语言

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

一、系统环境准备

  1. 更新系统并安装基础工具

    sudo apt update && sudo apt upgrade -y  
    sudo apt install -y build-essential git curl  
    
  2. 安装Node.js和npm

    • 推荐使用LTS版本(通过NodeSource安装):
      curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -  
      sudo apt install -y nodejs  
      
    • 验证安装:node -vnpm -v
  3. 安装PM2(进程管理工具)

    sudo npm install -g pm2  
    sudo pm2 startup systemd  # 设置开机自启  
    

二、部署项目代码

  1. 上传项目到服务器

    • SCP方式(本地→服务器):
      scp -r /本地/项目路径 username@服务器IP:/目标路径  
      
    • Git方式(推荐已有仓库的项目):
      git clone https://github.com/你的仓库地址.git  
      cd 项目目录  
      
  2. 安装项目依赖

    npm install --production  # 仅安装生产依赖  
    

三、启动项目

  1. 使用PM2启动应用
    pm2 start app.js --name "项目名"  # 直接启动JS文件  
    # 或启动npm脚本(如"npm start")  
    pm2 start "npm start" --name "项目名"  
    
  2. 保存进程列表并查看状态
    pm2 save  
    pm2 list  # 查看运行状态  
    pm2 logs  # 查看日志  
    

四、可选:配置Nginx反向代理(生产环境推荐)

  1. 安装Nginx

    sudo apt install nginx  
    
  2. 配置代理规则
    编辑配置文件(如/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  
    
  3. 配置SSL证书(可选)
    使用Let’s Encrypt免费证书:

    sudo apt install certbot python3-certbot-nginx  
    sudo certbot --nginx -d your-domain.com  
    

五、安全与维护

注意事项

以上步骤参考自,可根据项目具体需求调整。

0
看了该问题的人还看了