在阿里云Alibaba Cloud Linux 3.2104 LTS上如何部署Vue或React前端应用?

在阿里云 Alibaba Cloud Linux 3.2104 LTS 上部署 Vue 或 React 前端应用,通常是一个静态文件服务的过程。前端应用(Vue/React)通过构建生成静态资源(HTML、CSS、JS),然后使用 Web 服务器(如 Nginx)提供服务。

以下是完整的部署流程:


✅ 一、环境准备

  1. 登录 ECS 实例

    ssh root@your-ecs-ip
  2. 更新系统

    sudo yum update -y
  3. 安装 Node.js 和 npm(用于构建前端项目)

    推荐使用 NodeSource 提供的 Node.js 源:

    # 安装 Node.js 16(推荐 LTS 版本)
    curl -sL https://rpm.nodesource.com/setup_16.x | sudo bash -
    sudo yum install -y nodejs
    
    # 验证安装
    node --version
    npm --version

✅ 二、上传并构建前端项目

方式一:在服务器上直接构建(适合开发测试)

  1. 克隆或上传代码到服务器

    git clone https://github.com/yourusername/your-vue-or-react-app.git /opt/frontend-app
    cd /opt/frontend-app
  2. 安装依赖并构建

    npm install
    npm run build
    • Vue:npm run build → 输出到 dist/
    • React:npm run build → 输出到 build/

    构建完成后,会生成一个静态目录(如 distbuild),里面包含 index.htmlstatic/ 等文件。


方式二:本地构建后上传(推荐生产环境)

更安全的方式是在本地或 CI/CD 流程中构建,然后将 dist 目录上传到服务器:

# 本地执行
npm run build
scp -r dist/* user@your-ecs-ip:/var/www/html/

✅ 三、安装并配置 Nginx

  1. 安装 Nginx

    sudo yum install -y nginx
  2. 启动并设置开机自启

    sudo systemctl start nginx
    sudo systemctl enable nginx
  3. 配置 Nginx 服务静态文件

    编辑默认配置:

    sudo vim /etc/nginx/conf.d/default.conf

    内容示例(以 Vue/React 的 dist 目录为例):

    server {
        listen 80;
        server_name your-domain.com;  # 或你的公网 IP
    
        root /var/www/html;          # 静态文件存放路径
        index index.html;
    
        location / {
            try_files $uri $uri/ /index.html;  # 支持前端路由(SPA)
        }
    
        # 可选:静态资源缓存
        location ~* .(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }
  4. 创建目录并复制构建文件

    sudo mkdir -p /var/www/html
    sudo cp -r /opt/frontend-app/dist/* /var/www/html/
  5. 重启 Nginx

    sudo systemctl restart nginx

✅ 四、开放防火墙端口

确保阿里云安全组允许 80 端口(HTTP) 访问。

如果需要 HTTPS,可后续配置 SSL 证书(如 Let’s Encrypt + Certbot)。


✅ 五、访问应用

打开浏览器访问:

http://your-ecs-public-ip

你应该能看到你的 Vue 或 React 应用正常运行。


✅ 六、(可选)配置域名和 HTTPS

  1. 绑定域名:在 DNS 解析中将域名指向 ECS 公网 IP。
  2. 申请 SSL 证书
    sudo yum install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d your-domain.com

    自动配置 HTTPS 并启用自动续期。


✅ 总结

步骤 说明
1 安装 Node.js(用于构建)
2 构建 Vue/React 项目生成静态文件
3 安装 Nginx 并配置为静态服务器
4 将构建产物复制到 Nginx 目录
5 启动 Nginx,开放端口,访问页面

最佳实践建议

  • 生产环境建议使用 CI/CD(如 GitHub Actions + SCP)自动部署。
  • 不要在生产服务器上保留源码和 npm,只部署 dist 文件。
  • 使用 PM2 或 Docker 是可选方案,但对于纯前端静态应用,Nginx 足够高效。

如有后端 API,可单独部署在其他服务或同一服务器的不同端口,通过 Nginx 反向。

需要我提供自动化部署脚本或 Docker 部署方案吗?