使用容器进行 Angular 开发
先决条件
概述
在本节中,你将学习如何使用 Docker Compose 为容器化的 Angular 应用程序设置生产和开发环境。此设置允许你通过 Nginx 提供静态生产版本,并使用带有 Compose Watch 的实时重载开发服务器在容器内高效开发。
你将学习如何
- 为生产和开发配置单独的容器
- 在开发中使用 Compose Watch 启用自动文件同步
- 实时调试和实时预览更改,无需手动重新构建
自动更新服务(开发模式)
使用 Compose Watch 自动将源文件更改同步到容器化开发环境。这提供了无缝、高效的开发体验,无需手动重启或重建容器。
步骤 1:创建开发 Dockerfile
在项目根目录中创建一个名为 Dockerfile.dev 的文件,其内容如下
# =========================================
# Stage 1: Development - Angular Application
# =========================================
# Define the Node.js version to use (Alpine for a small footprint)
ARG NODE_VERSION=22.14.0-alpine
# Set the base image for development
FROM node:${NODE_VERSION} AS dev
# Set environment variable to indicate development mode
ENV NODE_ENV=development
# Set the working directory inside the container
WORKDIR /app
# Copy only the dependency files first to optimize Docker caching
COPY package.json package-lock.json ./
# Install dependencies using npm with caching to speed up subsequent builds
RUN --mount=type=cache,target=/root/.npm npm install
# Copy all application source files into the container
COPY . .
# Expose the port Angular uses for the dev server (default is 4200)
EXPOSE 4200
# Start the Angular dev server and bind it to all network interfaces
CMD ["npm", "start", "--", "--host=0.0.0.0"]此文件使用开发服务器为你的 Angular 应用程序设置一个轻量级开发环境。
步骤 2:更新你的 compose.yaml 文件
打开你的 compose.yaml 文件并定义两个服务:一个用于生产 (angular-prod),一个用于开发 (angular-dev)。
以下是 Angular 应用程序的示例配置
services:
angular-prod:
build:
context: .
dockerfile: Dockerfile
image: docker-angular-sample
ports:
- "8080:8080"
angular-dev:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "4200:4200"
develop:
watch:
- action: sync
path: .
target: /appangular-prod服务使用 Nginx 构建并提供静态生产应用。angular-dev服务运行你的 Angular 开发服务器,具有实时重新加载和热模块替换功能。watch触发与 Compose Watch 的文件同步。
注意有关更多详细信息,请参阅官方指南:使用 Compose Watch。
完成上述步骤后,你的项目目录现在应该包含以下文件
├── docker-angular-sample/
│ ├── Dockerfile
│ ├── Dockerfile.dev
│ ├── .dockerignore
│ ├── compose.yaml
│ ├── nginx.conf
│ └── README.Docker.md步骤 4:启动 Compose Watch
从项目根目录运行以下命令以在监视模式下启动容器
$ docker compose watch angular-dev
步骤 5:使用 Angular 测试 Compose Watch
要验证 Compose Watch 是否正常工作
在文本编辑器中打开
src/app/app.component.html文件。找到以下行
<h1>Docker Angular Sample Application</h1>更改为
<h1>Hello from Docker Compose Watch</h1>保存文件。
在浏览器中打开 https://:4200。
你应该会立即看到更新的文本出现,而无需手动重建容器。这确认了文件监视和自动同步按预期工作。
摘要
在本节中,你使用 Docker 和 Docker Compose 为你的 Angular 应用程序设置了完整的开发和生产工作流。
以下是你完成的工作
- 创建了
Dockerfile.dev以简化带有热重载的本地开发 - 在你的
compose.yaml文件中定义了单独的angular-dev和angular-prod服务 - 使用 Compose Watch 启用了实时文件同步,以获得更流畅的开发体验
- 通过修改和预览组件验证了实时更新的无缝工作
通过此设置,你现在可以完全在容器内构建、运行和迭代你的 Angular 应用,在不同环境中实现高效和一致。
相关资源
通过这些指南,加深你的知识并改进你的容器化开发工作流
- 使用 Compose Watch – 在开发过程中自动同步源更改
- 多阶段构建 – 创建高效、生产就绪的 Docker 镜像
- Dockerfile 最佳实践 – 编写干净、安全和优化的 Dockerfile。
- Compose 文件参考 – 学习在
compose.yaml中配置服务的完整语法和可用选项。 - Docker 卷 – 在容器运行之间持久化和管理数据
后续步骤
在下一节中,你将学习如何在 Docker 容器中运行 Angular 应用程序的单元测试。这确保了跨所有环境的一致测试,并消除了对本地机器设置的依赖。