温馨提示×

ubuntu js怎样部署项目

小樊
48
2026-10-28 14:03:56
栏目: 编程语言

在 Ubuntu 上部署 JavaScript 项目,通常分为 前端项目(如 Vue / React) 和 Node.js 后端项目 两类。下面给你一份实用、可操作的部署指南。


一、准备工作(通用)

1. 更新系统

sudo apt update
sudo apt upgrade -y

2. 安装 Node.js(推荐用 NodeSource)

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

验证:

node -v
npm -v

二、部署 Node.js 后端项目

1. 上传项目

scp -r yourproject user@server_ip:/var/www/yourproject

或 git 拉取:

git clone https://github.com/xxx/xxx.git
cd xxx
npm install

2. 启动项目(测试)

npm start

3. 使用 PM2 守护进程(推荐)

sudo npm install -g pm2
pm2 start app.js
pm2 startup
pm2 save

三、部署前端项目(Vue / React)

1. 构建项目

npm install
npm run build

生成目录一般是:

  • Vue:dist
  • React:build

2. 使用 Nginx 部署

安装 Nginx:

sudo apt install nginx

配置:

sudo vim /etc/nginx/sites-available/yourproject

示例:

server {
    listen 80;
    server_name yourdomain.com;

    root /var/www/yourproject/dist;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

启用:

sudo ln -s /etc/nginx/sites-available/yourproject /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

四、Node + Nginx(常见架构)

用户 → Nginx(80) → Node(3000)

Nginx 配置示例:

location /api/ {
    proxy_pass http://localhost:3000/;
}

五、使用 HTTPS(可选但推荐)

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx

六、常见问题

  • 端口被占用:sudo lsof -i:3000
  • 权限问题:用 www-data 或 pm2 启动
  • 防火墙:
sudo ufw allow 80
sudo ufw allow 443

如果你愿意,可以告诉我:

  • 是 前端 / 后端 / 全栈
  • 用的 框架(Vue / React / Express / Nest)
  • 是否 有域名 / 云服务器

我可以直接给你一份专属部署方案。

0 踩