在一台服务器上同时部署 Vue 前端和 Node.js 后端,核心思路是将两者作为独立的进程管理,并通过反向X_X(通常是 Nginx)进行流量分发。这种方式既保证了前后端解耦,又充分利用了服务器资源。
以下是基于生产环境标准的落地方案:
1. 架构设计
- Node.js 应用:运行在本地端口(如
3000),提供 API 接口。 - Vue 项目:构建为静态资源(HTML/CSS/JS),由 Nginx 直接托管或作为 SPA 路由处理。
- Nginx:作为反向X_X服务器,监听 80/443 端口,将
/api等请求转发给 Node.js,将其他请求转发给 Vue 静态文件。
2. 前置准备
确保服务器已安装必要软件(以 CentOS/Ubuntu 为例):
# 安装 Nginx, Node.js, PM2 (进程管理工具)
apt update && apt install nginx nodejs npm -y
npm install -g pm2
3. 后端部署 (Node.js)
假设后端代码位于 /var/www/myapp-backend。
-
安装依赖并启动:
cd /var/www/myapp-backend npm install # 使用 PM2 守护进程启动,设置端口为 3000 pm2 start server.js --name "backend-api" --node-args="--port=3000" pm2 save pm2 startup注意:生产环境务必配置环境变量(如
.env),避免硬编码敏感信息。 -
CORS 配置:
如果前端域名与后端不同,需在 Node.js 代码中配置 CORS 中间件(如使用cors包),允许跨域访问。
4. 前端部署 (Vue)
假设前端代码位于 /var/www/myapp-frontend。
-
打包构建:
在开发机或服务器上进行构建,生成dist目录。cd /var/www/myapp-frontend npm run build此时会生成一个包含
index.html,assets文件夹的dist目录。 -
处理 SPA 路由:
Vue 是单页应用(SPA),如果不做配置,刷新页面可能会报 404。需要在 Nginx 中配置try_files指令。
5. Nginx 反向X_X配置
编辑 Nginx 配置文件(通常在 /etc/nginx/sites-available/default 或新建 /etc/nginx/conf.d/myapp.conf)。
server {
listen 80;
server_name your-domain.com; # 替换为你的域名或 IP
# 前端静态资源配置
location / {
root /var/www/myapp-frontend/dist;
index index.html;
# 关键配置:解决 Vue Router History 模式下的 404 问题
try_files $uri $uri/ /index.html;
}
# 后端 API X_X配置
location /api/ {
proxy_pass http://localhost:3000/; # 转发到 Node.js 服务
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;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 可选:针对特定路径的其他X_X逻辑
}
关键点说明:
location /:匹配所有非/api/的请求,返回 Vue 的静态文件。try_files ... /index.html:当用户刷新 URL 时,Nginx 找不到具体文件,统一返回index.html,让 Vue Router 接管路由解析。location /api/:拦截 API 请求,通过proxy_pass转发到 Node.js 进程。
6. 验证与优化
- 重载配置:
nginx -t # 检查语法是否正确 systemctl reload nginx - 防火墙设置:
确保云服务器安全组开放 80 (HTTP) 和 443 (HTTPS) 端口,3000 端口通常不需要对外暴露(由 Nginx X_X)。 - HTTPS 部署(推荐):
生产环境强烈建议使用 HTTPS。可以使用 Let’s Encrypt 的 Certbot 自动申请免费证书,并在 Nginx 中配置 SSL 重定向。
7. 进阶建议
- 多实例负载均衡:如果 Node.js 业务量大,可使用 PM2 的集群模式 (
pm2 start server.js -i max),配合 Nginx 的 upstream 模块实现负载均衡。 - Docker 化:为了环境一致性,可以将前后端分别打包成 Docker 镜像,使用 Docker Compose 编排,一键拉起 Nginx、Node、MySQL 等服务,便于迁移和维护。
- 日志管理:配置 Nginx 的 access_log 和 error_log,并接入 ELK 或简单的日志轮转策略,方便排查问题。
这种方案结构清晰、维护成本低,是国内云厂商(如阿里云 ECS、腾讯云 CVM)上最常见的部署模式之一。
CLOUD云枢