Debian 上部署 JavaScript 应用的实用指南
一 前置准备
- 更新系统并安装基础工具:sudo apt update && sudo apt upgrade -y
- 安装 Nginx 与 UFW:sudo apt install -y nginx ufw
- 放行访问端口(示例为 80/443,或自定义 8999):sudo ufw allow ‘Nginx Full’ 或 sudo ufw allow 8999
- 云服务器需同时在云平台安全组放行对应端口(如 80/443/8999)
二 部署前端静态站点 Vue React Vite
- 本地打包:在项目根目录执行 npm install 与 npm run build,生成 dist(或 build)目录
- 上传到服务器:推荐将打包产物放到 /var/www/your-frontend,可使用 SCP 或 SFTP 工具
- 配置 Nginx 站点:示例
- 端口与目录:listen 80; root /var/www/your-frontend; index index.html;
- SPA 路由:location / { try_files $uri $uri/ /index.html; }
- 静态资源缓存:location ~* .(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { expires 7d; add_header Cache-Control “public, max-age=604800”; }
- 可选反向代理:将 /api/ 转发到后端(如 http://localhost:3000)
- 生效配置:sudo nginx -t && sudo systemctl reload nginx
- 访问验证:http://服务器IP 或 http://服务器IP:8999;如需域名与 HTTPS,可用 Certbot:sudo apt install -y certbot python3-certbot-nginx && sudo certbot --nginx -d yourdomain.com
三 部署 Node.js 后端服务 Express NestJS Fastify
- 安装 Node.js(二选一)
- APT 安装:sudo apt install -y nodejs npm
- 指定版本(NodeSource):curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - && sudo apt-get install -y nodejs
- 上传代码并安装依赖:cd /path/to/app && npm ci --only=production
- 用 PM2 守护进程:sudo npm install -g pm2
- 启动:pm2 start app.js --name myapp 或 pm2 start npm --name myapp – run start
- 开机自启:pm2 startup && pm2 save
- 配置 Nginx 反向代理(端口示例 3000 → 80/443)
- server { listen 80; server_name your_domain_or_ip; location / { proxy_pass http://localhost: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; } }
- 生效:sudo nginx -t && sudo systemctl reload nginx
- 防火墙:sudo ufw allow ‘Nginx Full’
四 常见问题与快速排查
- 页面 403 Forbidden:目录权限不足,执行 sudo chown -R appuser:www-data /var/www/your-frontend && sudo chmod -R 755 /var/www/your-frontend
- SPA 刷新 404:Nginx 未配置 try_files,确保 location / { try_files $uri $uri/ /index.html; }
- 静态资源 404:核对 Nginx root 是否指向正确目录,并确认文件已上传
- 无法访问(超时):检查本机防火墙与云安全组是否放行 80/443/8999
- 查看错误日志:tail -f /var/log/nginx/error.log
五 生产建议
- 使用 NVM 管理多版本 Node.js,便于升级与回滚
- 前端构建产物仅上传 dist/build 目录内容,避免泄露源码
- 为接口统一加前缀(如 /api)并用 Nginx 反向代理到后端,避免跨域
- 开启 HTTPS(Certbot),并配置强缓存策略与 Gzip 压缩以提升性能与安全性