Skip to content

使用 Docker Compose 部署多个前端应用

在一个 docker-compose.yml 文件中部署多个前端应用,只要为每个前端项目单独定义一个服务,并分配不同的端口(或使用 Nginx 做统一入口代理)。


✅ 方案一:多个服务 + 不同端口(最简单)

🗂️ 示例目录结构

project-root/
├── app1/
│   ├── dist/
│   ├── Dockerfile
│   └── nginx.conf
├── app2/
│   ├── dist/
│   ├── Dockerfile
│   └── nginx.conf
└── docker-compose.yml

🧾 docker-compose.yml 示例

yaml
version: '3'

services:
  app1:
    build:
      context: ./app1
      dockerfile: Dockerfile
    ports:
      - "8081:80"
    container_name: app1
    restart: always

  app2:
    build:
      context: ./app2
      dockerfile: Dockerfile
    ports:
      - "8082:80"
    container_name: app2
    restart: always

📦 构建 & 启动

bash
docker-compose up --build -d

然后访问:


✅ 方案二:多个前端 + 一个 Nginx 网关(统一域名或端口)

适合需要统一访问入口(如 /app1/, /app2/),部署到真实服务器或内网时更优雅。

示例结构

project-root/
├── app1/dist/
├── app2/dist/
├── nginx/
│   └── nginx.conf
├── docker-compose.yml
└── nginx/Dockerfile

nginx.conf 示例(统一入口)

nginx
server {
  listen 80;

  location /app1/ {
    alias /usr/share/nginx/html/app1/;
    try_files $uri $uri/ /index.html;
  }

  location /app2/ {
    alias /usr/share/nginx/html/app2/;
    try_files $uri $uri/ /index.html;
  }
}

nginx Dockerfile

Dockerfile
FROM nginx:stable-alpine

COPY ./nginx.conf /etc/nginx/conf.d/default.conf
COPY ../app1/dist /usr/share/nginx/html/app1
COPY ../app2/dist /usr/share/nginx/html/app2

docker-compose.yml 示例

yaml
version: '3'

services:
  frontend:
    build:
      context: ./nginx
      dockerfile: Dockerfile
    ports:
      - "80:80"
    container_name: frontend-multi
    restart: always

然后你就可以通过:

访问两个前端项目。


🧠 总结

方式入口优点场景
不同服务,不同端口:8081, :8082简单易上手内部测试或本地部署
统一服务,路径区分/app1/, /app2/更适合上线需要对外统一域名的生产环境

Released under the MIT License.