在一台服务器上同时部署前端和后端服务是常见的做法。以下是详细的步骤和推荐方案:
1. 目录结构规划
/server-project
├── frontend/ # 前端代码
│ ├── dist/ # 构建后的静态文件
│ └── src/
├── backend/ # 后端代码
│ ├── app.js # 或 main.py、main.go 等
│ └── package.json
└── nginx.conf # Nginx 配置
2. 前端部署方案
方案一:使用 Nginx 托管静态文件
# nginx.conf
server {
listen 80;
server_name your-domain.com;
# 前端静态文件
location / {
root /path/to/frontend/dist;
try_files $uri $uri/ /index.html;
index index.html;
}
# API 请求X_X到后端
location /api/ {
proxy_pass http://localhost:3000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# WebSocket 支持
location /ws/ {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
方案二:后端服务直接托管前端
Node.js 示例:
const express = require('express');
const path = require('path');
const app = express();
// 托管前端静态文件
app.use(express.static(path.join(__dirname, '../frontend/dist')));
// API 路由
app.get('/api/users', (req, res) => {
// 处理 API 请求
});
// 其他请求都返回前端页面(SPA)
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../frontend/dist/index.html'));
});
app.listen(3000);
3. 后端服务部署
使用 PM2 管理 Node.js 应用
# 安装 PM2
npm install -g pm2
# 启动后端服务
pm2 start backend/app.js --name "backend"
# 设置开机自启
pm2 startup
pm2 save
Python Flask/Django 示例
# 使用 Gunicorn
gunicorn -w 4 -b 0.0.0.0:3000 backend.wsgi:application
# 或使用 systemd 服务
sudo systemctl enable gunicorn
4. 完整部署流程
步骤 1:构建前端
cd frontend
npm run build # 生成 dist 目录
步骤 2:启动后端服务
# 方法一:使用 PM2
pm2 start backend/app.js --name backend --port 3000
# 方法二:使用 systemd
# 创建 /etc/systemd/system/backend.service
[Unit]
Description=Backend Service
After=network.target
[Service]
Type=simple
User=www-data
WorkingDirectory=/path/to/backend
ExecStart=/usr/bin/node app.js
Restart=always
[Install]
WantedBy=multi-user.target
步骤 3:配置 Nginx
# 安装 Nginx
sudo apt-get install nginx
# 配置站点
sudo cp nginx.conf /etc/nginx/sites-available/default
sudo nginx -t # 测试配置
sudo systemctl restart nginx
5. 端口规划建议
| 服务 | 端口 | 说明 |
|---|---|---|
| Nginx | 80/443 | 对外服务 |
| 后端 API | 3000 | 内部端口 |
| 数据库 | 3306/5432 | 内部访问 |
| Redis | 6379 | 缓存 |
6. 安全配置
HTTPS 配置
server {
listen 443 ssl;
server_name your-domain.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# 其他配置...
}
防火墙设置
# 只开放必要端口
sudo ufw allow 80
sudo ufw allow 443
sudo ufw deny 3000 # 后端端口不对外暴露
sudo ufw enable
7. 自动化部署脚本
#!/bin/bash
# deploy.sh
echo "开始部署..."
# 进入项目目录
cd /path/to/server-project
# 拉取最新代码
git pull origin main
# 构建前端
cd frontend
npm install
npm run build
# 重启后端服务
cd ../backend
pm2 reload backend
echo "部署完成!"
8. 监控和日志
# 查看 PM2 进程
pm2 list
pm2 logs backend
# 查看 Nginx 日志
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
注意事项
- 跨域问题:通过 Nginx 反向X_X解决 CORS
- 性能优化:开启 Nginx 缓存、Gzip 压缩
- 备份策略:定期备份数据库和重要文件
- 监控告警:设置服务健康检查
- 资源隔离:合理分配 CPU 和内存资源
这样就能在单台服务器上安全、高效地运行前后端服务了。
云小栈