加油
努力

前端项目部署时,多个应用如何共用一台服务器?

在前端项目部署时,多个应用共用一台服务器是常见需求。以下是几种主流且高效的实现方式:


✅ 1. 使用 Nginx 反向X_X(推荐)

这是最常用、最灵活的方式。通过 Nginx 将不同域名或路径请求转发到不同的前端应用。

示例场景:

  • app1.example.com → 应用 A
  • app2.example.com → 应用 B
  • example.com/admin → 管理后台
  • example.com/api → 后端接口

Nginx 配置示例:

server {
    listen 80;
    server_name app1.example.com;

    location / {
        root /var/www/app1;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

server {
    listen 80;
    server_name app2.example.com;

    location / {
        root /var/www/app2;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

# 路径区分:example.com/admin → 管理后台
server {
    listen 80;
    server_name example.com;

    location /admin/ {
        alias /var/www/admin/;
        index index.html;
        try_files $uri $uri/ /admin/index.html;
    }

    location /app1/ {
        alias /var/www/app1/;
        index index.html;
        try_files $uri $uri/ /app1/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;
    }
}

✅ 优点:支持多域名、路径路由、HTTPS、负载均衡、缓存等
🔧 注意:静态资源路径需配置正确(如 alias vs root


✅ 2. 基于子路径的单入口应用聚合

所有应用部署在同一个域名下,通过不同路径访问。

示例:

  • https://example.com/app1/
  • https://example.com/app2/

实现要点:

  • 每个前端应用构建时设置 publicPathbase(Vue/React/Vite)

    • Vue CLI: vue.config.js
      module.exports = {
        publicPath: '/app1/'
      }
    • Vite: vite.config.js
      export default {
        base: '/app1/'
      }
    • React (Create React App): 在 package.json 中设置 "homepage": "/app1/"
  • Nginx 配置:

    location /app1/ {
        root /var/www;
        try_files $uri $uri/ /app1/index.html;
    }

✅ 3. Docker + Nginx 组合部署

每个前端应用打包为独立 Docker 镜像,通过 Docker Compose 统一管理。

目录结构:

/docker-compose.yml
/nginx/
  /conf.d/
    default.conf
/app1/
  Dockerfile
/app2/
  Dockerfile

docker-compose.yml 示例:

version: '3'
services:
  app1:
    build: ./app1
    ports: []
  app2:
    build: ./app2
    ports: []
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx/conf.d:/etc/nginx/conf.d
    depends_on:
      - app1
      - app2

Nginx 配置反向X_X到 http://app1, http://app2 容器。

✅ 优势:环境隔离、易于扩展、适合微前端架构


✅ 4. 微前端架构(高级方案)

使用 qiankun、Module Federation 等技术,在一个主应用中动态加载多个子应用。

特点:

  • 所有子应用可独立开发、部署
  • 主应用负责路由分发和生命周期管理
  • 共享依赖、样式隔离

📌 适用场景:大型系统、中台架构


✅ 5. CDN + 静态托管服务(简化运维)

将不同应用部署到 CDN 或静态托管平台(如:

  • Vercel
  • Netlify
  • AWS S3 + CloudFront
  • 阿里云 OSS + CDN

然后通过 Nginx 或 DNS 做统一入口跳转或反向X_X。


⚠️ 注意事项

  1. 端口冲突:确保每个服务监听不同端口(或由 Nginx 统一暴露 80/443)
  2. 跨域问题:API 请求通过 Nginx X_X解决 CORS
  3. 资源路径:构建时注意 basepublicPath 设置
  4. HTTPS:使用 Let’s Encrypt + Certbot 自动配置 SSL
  5. 缓存策略:合理设置静态资源缓存头

✅ 推荐方案总结

场景 推荐方案
多个独立项目 Nginx 反向X_X(按域名或路径)
单一域名下多个子应用 路径区分 + 构建配置 base
团队协作/持续集成 Docker + Nginx
大型复杂系统 微前端架构
快速上线 Vercel/Netlify + 自定义域名

如有具体技术栈(Vue/React/Vite等),可提供更详细的配置建议。

云服务器